BIO+线程池实现简单的Server

public class MyServer {
  public static void main(String[] args) throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(100);

    ServerSocket serverSocket = new ServerSocket(8888);
    while (!Thread.currentThread().isInterrupted()) {
      Socket socket = serverSocket.accept();
      executor.submit(new ConnectIOnHandler(socket));
    }
  }
}
public class ConnectIOnHandler implements Runnable {
  private Socket socket;
  public ConnectIOnHandler(Socket socket) {
    this.socket = socket;
  }
  public void run() {
    try {
      while (!Thread.currentThread().isInterrupted() && !socket.isClosed()) {
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter pr = new PrintWriter(socket.getOutputStream(), true);
        String request;
        String response;

        while ((request = br.readLine()) != null) {
          if ("Done".equals(request)) {
            socket.close();
            break;
          }
          // 处理request,构造response
          System.out.println("客户端 Message: " + request);
          response = request;
          pr.println(response);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
展开阅读全文

没有更多推荐了,返回首页