Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 433
Toan Le Avatar asked Feb 18 '26 06:02

Toan Le


1 Answers

You have to use Non Blocking IO (NIO) library for this. You can follow this nice tutorial http://tutorials.jenkov.com/java-nio/index.html

like image 138
Dilip Kumar Avatar answered Feb 20 '26 18:02

Dilip Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!