こんにちは、それで私はこれをまっすぐにしましょう。あなたがしたいのは、複数のポートでリッスンできるサーバーを作成することです。新しい接続を取得したときに、その接続が使用したポートを識別できるようにしたいのですが、これは正しいですか?その場合は、java.nioパッケージを使用してこれを非常に簡単に行うことができます。
準備の選択にはセレクターを使用し、着信接続をリッスンするには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パッケージを使用して、複数のポートでリッスンできるノンブロッキング非同期サーバーを作成する方法を理解できます。