Java Server – Multiple ports?

It’s not possible to for a single instance of ServerSocket to listen to multiple ports. You can of course have multiple ServerSockets. However, as you already know, ServerSocket.accept blocks.

What you can use instead is a ServerSocketChannel. They’re used in a similar way, but do not block.

If there are no pending connections when ServerSocketChannel.accept is called then it simply returns null.

You can use with a Selector which takes a set of channels and blocks until at least one has a pending connection.

I don’t remember the specifics on how to use them, but this seems to be a decent code example.

edit: Here is my own example (pseudo-ish)

Selector selector =;

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

for (int port : ports) {
   ServerSocketChannel server =;

   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()) {;
   Set readyKeys = selector.selectedKeys();
   Iterator iterator = readyKeys.iterator();
   while (iterator.hasNext()) {
      SelectionKey key = (SelectionKey);
      if (key.isAcceptable()) {
         SocketChannel client = server.accept();
         Socket socket = client.socket();
// create new thread to deal with connection (closing both socket and client when done)

// tidy up selector and channels

Leave a Comment