javamultithreadingsocketsnetworkingdatagram

Thread Pools with many socket connections InputStream read method


The ServerSocket object's accept() method returns a Socket object that contains an `InputStream.'

Assuming I have many possible TCP connections to my ServerSocket, I would like a single thread to be blocked and waiting on any message received from those established Sockets. Once any message is received from anyone, go ahead and read it and then dispatch it or do what ever needs to be done. Then that single thread would block again until either that Socket or another Socket sends some data.

Can this be done?

For example, if this was UDP traffic and I was using a DatagramSocket I could just use it's receive() method in a loop.

DatagramSocket s = new DatagramSocket(4444);

while(true)
{
    //thread blocks and waits here... any client can send it data, and will only trigger on data being sent
    s.receive()
}

I want to avoid looping over all my connections and then testing each time in a non-blocking read() method from their InputStream. I don't want a thread just spinning for no reason.


Solution

  • You need to use NIO Selectors.

    So you create a selector and listen for events on that selector.

    Then you create e.g. a server socket and regular sockets and register them on the selector so that events are produced on that selector.

    This way you can have a single thread, processing many many connections. For more information see https://www.baeldung.com/java-nio-selector

    On Linux, under the hood, Epoll is used for network traffic.