Accept ServerSocket connection for multiple ports

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

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



In this block of code, it always expects the sellerSocket to connect first before accepting the buyerSocket. Can anyone suggest a way to accept whichever comes first?

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


source to share

2 answers

The only way to do this is by using multithreading, because the accept () method blocks until a connection is made.



You need to use the Non Blocking IO (NIO) library for this. You can follow this nice tutorial



All Articles