Search code examples
javatcpconcurrencyserversocket

Accept ServerSocket connection for multiple port


buyerSocket = new ServerSocket(BUYER_PORT);
sellerSocket = new ServerSocket(SELLER_PORT);
Socket clientSocket = null;
while (true)
    {
        clientSocket = sellerSocket.accept();
        MultiServerThread x = new MultiServerThread(clientSocket, dat);
        x.start();

        clientSocket = buyerSocket.accept();
        MultiServerThread y = new MultiServerThread(clientSocket, dat);
        y.start();

    }

In this block of code, it always waits for the sellerSocket to connect first before accepting buyerSocket. Could anyone suggest a way to accept whichever come first?

As for the description of accept() - Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made. Should I use another method instead of accept() if I want to accept connection from multiple ports?


Solution

  • The only way to do this is to use multithreading, because the accept() method blocks until a connection comes in.