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;
}
System.out.println("客户端 Message: " + request);
response = request;
pr.println(response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}