java socket 服務端併發處理 與 執行緒池的使用
package yiwangzhibujian.threadserver;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SocketServer {
public static void main(String args[]) throws Exception {
// 監聽指定的埠
int port = 55533;
ServerSocket server = new ServerSocket(port);
// server將一直等待連線的到來
System.out.println("server將一直等待連線的到來");
//如果使用多執行緒,那就需要執行緒池,防止併發過高時建立過多執行緒耗盡資源
ExecutorService threadPool = Executors.newFixedThreadPool(100);
while (true) {
Socket socket = server.accept();
Runnable runnable=()->{
try {
// 建立好連線後,從socket中獲取輸入流,並建立緩衝區進行讀取
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int len;
StringBuilder sb = new StringBuilder();
while ((len = inputStream.read(bytes)) != -1) {
// 注意指定編碼格式,傳送方和接收方一定要統一,建議使用UTF-8
sb.append(new String(bytes, 0, len, "UTF-8"));
}
System.out.println("get message from client: " + sb);
inputStream.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
};
threadPool.submit(runnable);
}
}
}