一、服务端回传服务类 :
impor java.io.ioException; impor java.io.inputstream; impor java.io.outputStream; impor java.net.socket; impor java.util.logging.level; impor java.util.logging.logger; echoprotocol kelas publik mengimplementasikan runnable {private static final int bufsize = 32; // ukuran (dalam byte) dari I/O buffer soket klien soket soket; // Socket Connect ke Client Private Logger Logger; // server logger echoprotocol (socket clientocket, logger logger) {this.clientsocket = clientsocket; this.logger = logger; } public static void handleChoClient (socket clientsocket, logger logger) {coba {// Dapatkan input dan output stream I/O output dari socket inputStream in = clientocket.getInputStream (); OutputStream out = clientocket.getoutputStream (); int recvmsgsize; // Ukuran pesan yang diterima int TotalBytesechoed = 0; // byte yang diterima dari klien byte [] echobuffer = byte baru [bufsize]; // menerima buffer // terima sampai klien menutup koneksi, ditunjukkan oleh -1 while ((recvmsgsize = in.read (echoBuffer))! = -1) {out.write (echobuffer, 0, recvmsgsize); TotalByteseChoed += RecVMSgSize; } logger.info ("klien" + clientocket.getRemotesocketAddress () + ", echoed" + totalBytesechoed + "bytes."); } catch (ioException ex) {logger.log (level.warning, "pengecualian dalam protokol gema", ex); } akhirnya {coba {clientocket.close (); } catch (ioException e) {}}} public void run () {handleechoclient (this.clientsocket, this.logger); }}二、每个客户端请求都新启一个线程的 TCP 服务端 :
impor java.io.ioException; impor java.net.serversocket; impor java.net.socket; impor java.util.logging.logger; Kelas Publik TCPechoServerThread {public static void main (String [] args) melempar ioException {// Buat soket server untuk menerima permintaan koneksi klien server serversock = server baru (5500); Logger logger = logger.getLogger ("praktis"); // jalankan selamanya, menerima dan memalsukan utas untuk setiap koneksi sementara (true) {socket clntsock = servsock.accept (); // blok menunggu koneksi // spawn thread untuk menangani utas koneksi baru utas = utas baru (echoprotocol baru (clntsock, logger)); thread.start (); logger.info ("dibuat dan mulai utas" + thread.getName ()); } / * Tidak tercapai * /}}三、固定线程数的 TCP 服务端 :
impor java.io.ioException; impor java.net.serversocket; impor java.net.socket; impor java.util.logging.level; impor java.util.logging.logger; kelas publik tcpechoServerpool {public static void main (string [] args) melempar ioException {int threadPoolSize = 3; // Fixed ThreadPoolSize Server Final Servsock = New Serversocket (5500); Logger Final Logger = Logger.GetLogger ("Praktis"); // menelurkan sejumlah utas yang tetap untuk melayani klien untuk (int i = 0; i <threadPoolSize; i ++) {thread thread = thread baru () {public void run () {while (true) {coba {socket clntsock = servsock.accept (); // tunggu koneksi echoprotocol.handleechoclient (clntsock, logger); // menangani} catch (ioException ex) {logger.log (level.warning, "klien menerima gagal", ex); }}}}; thread.start (); logger.info ("dibuat dan mulai thread =" + thread.getName ()); }}}四、使用线程池 (使用 Spring 的线程次会有队列、最大线程数、最小线程数和超时时间的概念)
1. : :
impor java.util.concurrent.*; /** * 任务执行者 * * @author watson xu * @since 1.0.0 <p> 2013-6-8 上午 10:33:09 </p> */Public Class ThreadPoolTaskexecutor {private ThreadPoolTasExecutor () {} ExecutorService Private ExecutorService Executoror = Executors.neweCachecutor () {} Private ExecutorService Executorororororor = Executors.neweCach () {{Private Executorservice Executorororor = Executors.neweCached执行器会在需要自行任务而线程池中没有线程的时候来调用该程序。对于 Callable 类型的调用通过封装以后转化为 Runnable */Public Thread NewThread (Runnable R) {Count ++; public static void Invoke (Runnable Task, TimeUnit Unit, Long Timeout) Melempar TimeOutException, RunTimeException {Invoke (Tugas, Null, Unit, Timeout); } public static <T> t Invoke (tugas runnable, t hasil, unit timeUnit, waktu lama) melempar timeoutexception, runtimeException {future <t> future = executor.submit (tugas, hasil); T t = null; coba {t = found.get (timeout, unit); } catch (timeoutexception e) {lempar new timeoutexception ("Thread Invoke Timeout ..."); } catch (Exception e) {lempar runtimeException baru (e); } return t; } public static <T> t Invoke (Callable <T> Tugas, TimeUnit Unit, Long Timeout) Melempar TimeoutException, RunTimeException {// 这里将任务提交给执行器 , 任务已经启动 , 这里是异步的。 Future <T> Future = Executor.submit (Tugas); // System.out.println ("Tugas Aready in Thread"); T t = null; coba { / * * 这里的操作是确认任务是否已经完成 , 有了这个操作以后 * 1) 对 Invoke () 的调用线程变成了等待任务完成状态 * 2) 主线程可以接收子线程的处理结果 * / t = Future.get (timeout, unit); } catch (timeoutexception e) {lempar new timeoutexception ("Thread Invoke Timeout ..."); } catch (Exception e) {lempar runtimeException baru (e); } return t; }}2. 具有伸缩性的 TCP 服务端 :
impor java.io.ioException; impor java.net.serversocket; impor java.net.socket; impor java.util.concurrent.timeunit; impor java.util.logging.logger; impor demo.callable.threadpooltaskexecutor; kelas publik tcpechoServerexecutor {public static void main (string [] args) melempar ioException {// Buat soket server untuk menerima permintaan koneksi klien server server servsock = new Serverersocket (5500); Logger logger = logger.getLogger ("praktis"); // Jalankan selamanya, menerima dan memalukan utas untuk melayani setiap koneksi saat (true) {socket clntsock = servsock.accept (); // blok menunggu koneksi //executorservice.submit( echoprotocol (clntsock, logger)); coba {threadpooltaskexecutor.invoke (echoprotocol baru (clntsock, logger), timeunit.seconds, 3); } catch (Exception e) {} //service.execute(new Timelimitechoprotocol (clntsock, logger)); } / * Tidak tercapai * /}}以上就是本文的全部内容 , 查看更多 Java 的语法 , 大家可以关注 : 《Berpikir di Java 中文手册》、《 JDK 1.7 参考手册官方英文版》、《 JDK 1.6 API Java 中文参考手册》、《 JDK 1.5 API Java 中文参考手册》 , , ,