Search code examples
javaservernioports

Java - Server listens on many ports


I have some simple code in my server that waits for a client to connect on port 4444

try {
  serverSocket = new ServerSocket(4444);
  } catch (IOException e) {
    //blah
}

while (true) {
  try {
    clientSocket = serverSocket.accept();
    //do something
} catch (IOException ex) {
    //blah
}

I now what to expand to have my server listen on 10 different ports. At first I was looking at something like: for (int i = 4444; i < 4454; i++) but that didn't work properly.

Now I'm looking into Java NIO ServerSocketChannel. I found this code online (thanks @Dunes!)

Selector selector = Selector.open();

int[] ports = {4000,4001,6000};

for (int port : ports) {
   ServerSocketChannel server = ServerSocketChannel.open();
   server.configureBlocking(false);

   server.socket().bind(new InetSocketAddress(port));
   // we are only interested when accept evens occur on this socket
   server.register(selector, SelectionKey.OP_ACCEPT); 
}

while (selector.isOpen()) {
   selector.select();
   Set readyKeys = selector.selectedKeys();
   Iterator iterator = readyKeys.iterator();
   while (iterator.hasNext()) {
      SelectionKey key = (SelectionKey) iterator.next();
      if (key.isAcceptable()) {
         SocketChannel client = server.accept(); //SERVER CANNOT BE RESOLVED!!!!
         Socket socket = client.socket();
         // create new thread to deal with connection (closing both socket and client when done)
      }
   }
}

But I can't execute it. On the while (iterator.hasNext()) block, server in server.accept says that "server cannot be resolved". Why is that? Is NIO ServerSocketChannel the right thing I'm suppose to be doing to have my server listen on many ports? If not, what's the best method for my server to accept many ports?


Solution

  • I don't know why you think you need this, but your compilation error should be resolved as follows:

    ServerSocketChannel server = (ServerSocketChannel)key.channel();
    SocketChannel client = server.accept();