Choosing between multiple sockets that are ready to be read from

I am writing a server-client application. I have a server that contains multiple sockets which I got from the accept () ServerSocket method. I want to read from these sockets, but I don't know which socket is ready to read. I need some sort of selector that will select one of the sockets ready to read, so I can read the data sent to them.



source to share

1 answer

You basically have two options to make it work:

  • Have a dedicated thread for each socket. This is because "regular" socket I / O is blocked. You cannot selectively handle multiple sockets with a single thread. And since there is no peeping functionality, you always run the risk of getting a lock when called read

    . By having a stream for each socket that you are interested in reading, blocking reads will not block other operations (threads).
  • Use NIO. NIO allows for asynchronous I / O and basically exactly what you asked for - a selector.

If you decide to go the NIO-way, I would recommend checking out MINA and Netty . I found them much easier to work with than a simple NIO. Not only will you get a nicer API to work with, but at least MINA had workarounds for some nasty NIO bugs too.



All Articles