• 客户端
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
public static void client() {
try {
//获取客户端通道
SocketChannel sc = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8899));
//切换到非阻塞模式
sc.configureBlocking(false);
//分配指定大学缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
//发送数据给服务端
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
String str = scan.nextLine();
buf.put((LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ":" + str).getBytes());
buf.flip();
sc.write(buf);
buf.clear();
if (str.equals("exit")) {
break;
}
}
sc.close();
} catch (IOException e) {
e.printStackTrace();
}


}
  • 服务端
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
public void server() {
try {
//获取客户端通道
ServerSocketChannel ssc = ServerSocketChannel.open();
//切换到非阻塞模式
ssc.configureBlocking(false);

ssc.bind(new InetSocketAddress(8899));

Selector selector = Selector.open();
//将通道注册到选择器中去 并指定监听“接收事件”
ssc.register(selector, SelectionKey.OP_ACCEPT);

//轮询获取选择器上已经 准备就绪 的事件
while (selector.select() > 0) {
//获取当前选择器中所有注册的 已就绪的监听事件
Iterator<SelectionKey> its = selector.selectedKeys().iterator();
while (its.hasNext()) {
//获取准备就绪的事件
SelectionKey sk = its.next();
//判断具体就绪事件
if (sk.isAcceptable()) {
SocketChannel sc = ssc.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
} else if (sk.isReadable()) {
//获取当前选择器上 读就绪 的通道
SocketChannel sc = (SocketChannel) sk.channel();
//读取数据
ByteBuffer buf = ByteBuffer.allocate(1024);
int len;
while ((len = sc.read(buf)) > 0) {
buf.flip();
System.out.println(new String(buf.array(), 0, len));
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
buf.clear();
}
}
//取消选择键
its.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}

}