NIOServer.java
3.5 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package two;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class NIOServer {
private Selector selector;
private Map<SocketChannel, String> clients = new HashMap<>();
public void start(int port) throws IOException {
// 创建ServerSocketChannel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false);
// 创建Selector
selector = Selector.open();
// 注册ServerSocketChannel到Selector上,监听ACCEPT事件
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server started...");
// 循环处理事件
while (true) {
// 调用select方法阻塞,等待事件发生
selector.select();
Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
keyIterator.remove();
if (key.isAcceptable()) { // 处理ACCEPT事件
handleAccept(key);
} else if (key.isReadable()) { // 处理READ事件
handleRead(key);
}
}
}
}
private void handleAccept(SelectionKey key) throws IOException {
// 获取ServerSocketChannel
ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
// 接受客户端连接
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
// 注册SocketChannel到Selector上,监听READ事件
socketChannel.register(selector, SelectionKey.OP_READ);
System.out.println("Client " + socketChannel.getRemoteAddress() + " connected.");
// 将新连接的客户端添加到clients列表中
clients.put(socketChannel, socketChannel.getRemoteAddress().toString());
}
private void handleRead(SelectionKey key) throws IOException {
// 获取SocketChannel
SocketChannel socketChannel = (SocketChannel) key.channel();
// 读取数据
ByteBuffer buffer = ByteBuffer.allocate(1024);
int numRead = socketChannel.read(buffer);
if (numRead == -1) { // 客户端关闭连接
key.cancel();
clients.remove(socketChannel);
System.out.println("Client " + socketChannel.getRemoteAddress() + " disconnected.");
socketChannel.close();
return;
}
// 将数据转发给其他客户端
String message = new String(buffer.array(), 0, numRead).trim();
System.out.println("Received message from " + socketChannel.getRemoteAddress() + ": " + message);
for (SocketChannel client : clients.keySet()) {
if (client != socketChannel) {
ByteBuffer writeBuffer = ByteBuffer.wrap(message.getBytes());
client.write(writeBuffer);
}
}
}
public static void main(String[] args) throws IOException {
NIOServer server = new NIOServer();
server.start(8888);
}
}