-
Notifications
You must be signed in to change notification settings - Fork 267
Expand file tree
/
Copy pathEchoServer.java
More file actions
52 lines (48 loc) · 1.62 KB
/
Copy pathEchoServer.java
File metadata and controls
52 lines (48 loc) · 1.62 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
package com.javaedge.concurrency.threadpermessage;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
/**
* 回显从客户端收到的数据
*
* @author JavaEdge
*/
public final class EchoServer {
public static void main(String[] args) throws Exception {
final ServerSocketChannel ssc = ServerSocketChannel.open().bind(
new InetSocketAddress(8080));
// 处理请求
try {
while (true) {
// 接收请求
SocketChannel sc = ssc.accept();
// 每个请求都创建一个线程
new Thread(() -> {
try {
// 读Socket
ByteBuffer rb = ByteBuffer.allocateDirect(1024);
sc.read(rb);
//模拟处理请求
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 写Socket
ByteBuffer wb = (ByteBuffer) rb.flip();
sc.write(wb);
// 关闭Socket
sc.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}).start();
}
} finally {
ssc.close();
}
}
}