MultiThreadClientHandler.java
上传用户:caijun
上传日期:2022-08-05
资源大小:13k
文件大小:3k
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.net.*;
- import java.util.concurrent.*;
- public class MultiThreadClientHandler {
- private int port = 8821;
- private ServerSocket serverSocket;
- private ExecutorService executorService;// thread pool
- private final int POOL_SIZE = 10;// thread numbers of a single pool
- public MultiThreadClientHandler() throws IOException {
- serverSocket = new ServerSocket(port);
- // Runtime的availableProcessor()方法返回当前系统的CPU数目.
- executorService = Executors.newFixedThreadPool(Runtime.getRuntime()
- .availableProcessors()
- * POOL_SIZE);
- System.out.println("服务器启动n"
- + Runtime.getRuntime().availableProcessors() * POOL_SIZE);
- }
- public void service() {
- while (true) {
- Socket socket = null;
- try {
- // 接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接
- socket = serverSocket.accept();
- executorService.execute(new Handler(socket));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) throws IOException {
- new MultiThreadClientHandler().service();
- }
- }
- class Handler implements Runnable {
- private Socket socket;
- public Handler(Socket socket) {
- this.socket = socket;
- }
- private PrintWriter getWriter(Socket socket) throws IOException {
- OutputStream socketOut = socket.getOutputStream();
- return new PrintWriter(socketOut, true);
- }
- private BufferedReader getReader(Socket socket) throws IOException {
- InputStream socketIn = socket.getInputStream();
- return new BufferedReader(new InputStreamReader(socketIn));
- }
- public String echo(String msg) {
- return "echo:" + msg;
- }
- public void run() {
- try {
- System.out.println("New connection accepted "
- + socket.getInetAddress() + ":" + socket.getPort());
- BufferedReader br = getReader(socket);
- PrintWriter pw = getWriter(socket);
- String msg = null;
- System.out.println("n++n");
- if(br.readLine().equals(null)){
- System.out.println("n-----n");
- }else{
- System.out.println("n" + br.readLine().trim() + "n");
- }
-
- while ((msg = br.readLine()) != null) {
- System.out.println(msg);
- pw.println(echo(msg));
- if (msg.equals("bye"))
- break;
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (socket != null)
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }