一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務(wù)器之家 - 編程語(yǔ)言 - JAVA教程 - Java Socket編程實(shí)例(三)- TCP服務(wù)端線程池

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

2020-05-17 12:17kingxss JAVA教程

這篇文章主要講解Java Socket編程中TCP服務(wù)端線程池的實(shí)例,希望能給大家做一個(gè)參考。

一、服務(wù)端回傳服務(wù)類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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);
  }
}

二、每個(gè)客戶端請(qǐng)求都新啟一個(gè)線程的Tcp服務(wù)端:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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服務(wù)端:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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的線程次會(huì)有隊(duì)列、最大線程數(shù)、最小線程數(shù)和超時(shí)時(shí)間的概念)

1.線程池工具類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.concurrent.*;
 
/**
 * 任務(wù)執(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í)行器會(huì)在需要自行任務(wù)而線程池中沒(méi)有線程的時(shí)候來(lái)調(diào)用該程序。對(duì)于callable類型的調(diào)用通過(guò)封裝以后轉(zhuǎn)化為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 {
    // 這里將任務(wù)提交給執(zhí)行器,任務(wù)已經(jīng)啟動(dòng),這里是異步的。
    Future<T> future = executor.submit(task);
    // System.out.println("Task aready in thread");
    T t = null;
    try {
      /*
       * 這里的操作是確認(rèn)任務(wù)是否已經(jīng)完成,有了這個(gè)操作以后
       * 1)對(duì)invoke()的調(diào)用線程變成了等待任務(wù)完成狀態(tài)
       * 2)主線程可以接收子線程的處理結(jié)果
       */
      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服務(wù)端:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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 */
  }
}

以上就是本文的全部?jī)?nèi)容,查看更多Java的語(yǔ)法,也希望大家多多支持服務(wù)器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产精品久久毛片完整版 | 91嫩草国产在线观看免费 | 无码AV免费精品一区二区三区 | 国产女主播在线播放一区二区 | 日本不卡在线观看免费v | 楚乔传第二部免费播放电视连续剧 | 高清男的插曲女的 欢迎你老狼 | 亚洲国产免费观看视频 | 亚洲a在线视频 | 99国产自偷色久 | 91精品国产91久久久久久 | 999精品视频在线观看热6 | 黑人性xxx| 娇妻被老外疯狂调教 | 国产成人手机在线好好热 | 国产99久久精品 | 欧美帅老头oldmangay | 欧美一级专区免费大片俄罗斯 | aaaa大片| 亚洲+欧美+国产+综合 | 欧美日韩一区视频 | aaaaa特级毛片 | 亚洲国产精久久久久久久 | 日韩欧美国内 | 欧美日韩一区二区三区在线视频 | 大陆国产精品视频 | 亚洲视频在线免费观看 | 四虎网址 | 成人午夜毛片 | 香蕉精品 | 婷婷久久精品 | 忘忧草在线社区WWW日本-韩国 | 午夜精品久久久久久 | 乳环贵妇堕落开发调教番号 | 日韩一区在线播放 | 99国产精品免费视频 | 国产在线成人精品 | 亚洲天堂男人的天堂 | 男人和女人上床 | 国产成人一区二区三区视频免费蜜 | 亚洲品质自拍网站 |