你好,让我直说吧。您要做的是创建一个可以侦听多个端口的服务器,并且当您获得新连接时,您希望能够知道该连接使用了哪个端口,这是正确的吗?如果是这样的话,您可以使用 java.nio 包轻松完成此操作。
我们将使用Selector 进行就绪选择,并使用ServerSocketChannel 侦听传入连接。
首先我们需要声明我们的Selector。
Selector selector = Selector.open();
现在让我们创建一个要监听的端口列表并开始监听它们。
int ports[] = new int[] { 1234, 4321 };
// loop through each port in our list and bind it to a ServerSocketChannel
for (int port : ports) {
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
serverChannel.socket().bind(new InetSocketAddress(port));
serverChannel.register(selector, SelectionKey.OP_ACCEPT);
}
现在是SelectionKey 处理过程。
while (true) {
selector.select();
Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
while (selectedKeys.hasNext()) {
SelectionKey selectedKey = selectedKeys.next();
if (selectedKey.isAcceptable()) {
SocketChannel socketChannel = ((ServerSocketChannel) selectedKey.channel()).accept();
socketChannel.configureBlocking(false);
switch (socketChannel.socket().getPort()) {
case 1234:
// handle connection for the first port (1234)
break;
case 4321:
// handle connection for the secon port (4321)
break;
}
} else if (selectedKey.isReadable()) {
// yada yada yada
}
}
}
对于这样一个简单的任务,可能不需要 switch 语句,但它是为了便于阅读和理解。
请记住,此服务器以非阻塞异步方式设置,因此您执行的所有 I/O 调用都不会阻塞当前线程。所以不要在SelectionKey处理过程中启动任何新线程。
另外,我知道这并不能完全回答您的问题(它可能会,也可能不会),但它实际上会让您了解如何使用 java.nio 包创建非阻塞异步服务器可以监听多个端口。