What will happen if two clients send request simultaneously to a ServerSocket that is using a while loop to accept requests

I've two clients on two different machines and I don't know when they're gonna send requests.

is this the scenario where I HAVE TO use Selector and ServerSocketChannel?

Example:

public class Server{

    public static void main(String[] args) {

        try(
            ServerSocket serverSocket = new ServerSocket(1234)
           ){

               while(true) {
                    serverSocket.accept();
                    Thread.sleep(5*1000);
                    //and while its sleeping, second client sends request
               }
           }catch(Exception e){}
    }
}
Jon Skeet
people
quotationmark

is this the scenario where I HAVE TO use Selector and ServerSocketChannel?

Nope. A more common solution is to have one thread per client - when you accept a call, create a new thread (or use an existing one from a thread-pool) and use that to handle that connection. The original thread calls accept again (immediately - no sleep required) and spawns a new thread for the next connection, etc.

(There are certainly advantages to asynchronous IO, but you're not forced to use it.)

people

See more on this question at Stackoverflow