-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathMultiThreadEchoServer.java
More file actions
63 lines (52 loc) · 1.88 KB
/
MultiThreadEchoServer.java
File metadata and controls
63 lines (52 loc) · 1.88 KB
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
package PracticeJavaHighConcurrency.chapter5;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MultiThreadEchoServer {
private static ExecutorService executorService = Executors.newCachedThreadPool();
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(8000);
Socket clientSocket = null;
System.out.println("Server listening ....");
while (true) {
clientSocket = ss.accept();
executorService.execute(new HandleMsg(clientSocket));
}
}
static class HandleMsg implements Runnable {
Socket clientSocket;
public HandleMsg(Socket clientSocket) {
this.clientSocket = clientSocket;
}
@Override
public void run() {
BufferedReader is = null;
PrintWriter os = null;
try {
long start = System.currentTimeMillis();
is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
os = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
while ((inputLine = is.readLine()) != null) {
os.println(inputLine);
}
System.out.println(String.format("Cost %s ms", (System.currentTimeMillis() - start)));
} catch (Exception e) {
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (Exception e) {
}
}
}
}
}