国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java Socket編程實例(三)- TCP服務端線程池

2019-11-26 14:11:37
字體:
來源:轉載
供稿:網友

一、服務端回傳服務類:

import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger;  public class EchoProtocol implements Runnable {   private static final int BUFSIZE = 32; // Size (in bytes) of I/O buffer   private Socket clientSocket; // Socket connect to client   private Logger logger; // Server logger    public EchoProtocol(Socket clientSocket, Logger logger) {     this.clientSocket = clientSocket;     this.logger = logger;   }    public static void handleEchoClient(Socket clientSocket, Logger logger) {     try {       // Get the input and output I/O streams from socket       InputStream in = clientSocket.getInputStream();       OutputStream out = clientSocket.getOutputStream();        int recvMsgSize; // Size of received message       int totalBytesEchoed = 0; // Bytes received from client       byte[] echoBuffer = new byte[BUFSIZE]; // Receive Buffer       // Receive until client closes connection, indicated by -1       while ((recvMsgSize = in.read(echoBuffer)) != -1) {         out.write(echoBuffer, 0, recvMsgSize);         totalBytesEchoed += recvMsgSize;       }        logger.info("Client " + clientSocket.getRemoteSocketAddress() + ", echoed " + totalBytesEchoed + " bytes.");            } catch (IOException ex) {       logger.log(Level.WARNING, "Exception in echo protocol", ex);     } finally {       try {         clientSocket.close();       } catch (IOException e) {       }     }   }    public void run() {     handleEchoClient(this.clientSocket, this.logger);   } } 

二、每個客戶端請求都新啟一個線程的Tcp服務端:

import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.logging.Logger;  public class TCPEchoServerThread {    public static void main(String[] args) throws IOException {     // Create a server socket to accept client connection requests     ServerSocket servSock = new ServerSocket(5500);      Logger logger = Logger.getLogger("practical");      // Run forever, accepting and spawning a thread for each connection     while (true) {       Socket clntSock = servSock.accept(); // Block waiting for connection       // Spawn thread to handle new connection       Thread thread = new Thread(new EchoProtocol(clntSock, logger));       thread.start();       logger.info("Created and started Thread " + thread.getName());     }     /* NOT REACHED */   } } 

三、固定線程數(shù)的Tcp服務端:

import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger;  public class TCPEchoServerPool {   public static void main(String[] args) throws IOException {     int threadPoolSize = 3; // Fixed ThreadPoolSize      final ServerSocket servSock = new ServerSocket(5500);     final Logger logger = Logger.getLogger("practical");      // Spawn a fixed number of threads to service clients     for (int i = 0; i < threadPoolSize; i++) {       Thread thread = new Thread() {         public void run() {           while (true) {             try {               Socket clntSock = servSock.accept(); // Wait for a connection               EchoProtocol.handleEchoClient(clntSock, logger); // Handle it             } catch (IOException ex) {               logger.log(Level.WARNING, "Client accept failed", ex);             }           }         }       };       thread.start();       logger.info("Created and started Thread = " + thread.getName());     }   } } 

四、使用線程池(使用Spring的線程次會有隊列、最大線程數(shù)、最小線程數(shù)和超時時間的概念)

1.線程池工具類:

import java.util.concurrent.*;  /**  * 任務執(zhí)行者  *  * @author Watson Xu  * @since 1.0.0 <p>2013-6-8 上午10:33:09</p>  */ public class ThreadPoolTaskExecutor {    private ThreadPoolTaskExecutor() {    }    private static ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {     int count;      /* 執(zhí)行器會在需要自行任務而線程池中沒有線程的時候來調用該程序。對于callable類型的調用通過封裝以后轉化為runnable */     public Thread newThread(Runnable r) {       count++;       Thread invokeThread = new Thread(r);       invokeThread.setName("Courser Thread-" + count);       invokeThread.setDaemon(false);// //????????????        return invokeThread;     }   });    public static void invoke(Runnable task, TimeUnit unit, long timeout) throws TimeoutException, RuntimeException {     invoke(task, null, unit, timeout);   }    public static <T> T invoke(Runnable task, T result, TimeUnit unit, long timeout) throws TimeoutException,       RuntimeException {     Future<T> future = executor.submit(task, result);     T t = null;     try {       t = future.get(timeout, unit);     } catch (TimeoutException e) {       throw new TimeoutException("Thread invoke timeout ...");     } catch (Exception e) {       throw new RuntimeException(e);     }     return t;   }    public static <T> T invoke(Callable<T> task, TimeUnit unit, long timeout) throws TimeoutException, RuntimeException {     // 這里將任務提交給執(zhí)行器,任務已經啟動,這里是異步的。     Future<T> future = executor.submit(task);     // System.out.println("Task aready in thread");     T t = null;     try {       /*        * 這里的操作是確認任務是否已經完成,有了這個操作以后        * 1)對invoke()的調用線程變成了等待任務完成狀態(tài)        * 2)主線程可以接收子線程的處理結果        */       t = future.get(timeout, unit);     } catch (TimeoutException e) {       throw new TimeoutException("Thread invoke timeout ...");     } catch (Exception e) {       throw new RuntimeException(e);     }      return t;   } } 

2.具有伸縮性的Tcp服務端:

import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.TimeUnit; import java.util.logging.Logger;  import demo.callable.ThreadPoolTaskExecutor;   public class TCPEchoServerExecutor {    public static void main(String[] args) throws IOException {     // Create a server socket to accept client connection requests     ServerSocket servSock = new ServerSocket(5500);      Logger logger = Logger.getLogger("practical");          // Run forever, accepting and spawning threads to service each connection     while (true) {       Socket clntSock = servSock.accept(); // Block waiting for connection       //executorService.submit(new EchoProtocol(clntSock, logger));       try {         ThreadPoolTaskExecutor.invoke(new EchoProtocol(clntSock, logger), TimeUnit.SECONDS, 3);       } catch (Exception e) {       }        //service.execute(new TimelimitEchoProtocol(clntSock, logger));     }     /* NOT REACHED */   } } 

以上就是本文的全部內容,查看更多Java的語法,大家可以關注:《Thinking in Java 中文手冊》、《JDK 1.7 參考手冊官方英文版》、《JDK 1.6 API java 中文參考手冊》、《JDK 1.5 API java 中文參考手冊》,也希望大家多多支持武林網。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 仁布县| 舒城县| 承德市| 孟连| 盐亭县| 隆化县| 石屏县| 台东县| 秭归县| 尉犁县| 高雄市| 东海县| 湾仔区| 大连市| 广平县| 南安市| 玉龙| 岳普湖县| 贵州省| 普兰县| 宁河县| 田东县| 鲜城| 昌江| 吉隆县| 禄劝| 台江县| 大关县| 东丽区| 通榆县| 克拉玛依市| 上林县| 鹤峰县| 孟津县| 台中市| 策勒县| 隆尧县| 习水县| 察隅县| 肇州县| 精河县|