Toan Le
Toan Le

Reputation: 421

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?

Upvotes: 3

Views: 911

Answers (2)

Dilip Kumar
Dilip Kumar

Reputation: 2534

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

Upvotes: 1

Distjubo
Distjubo

Reputation: 1009

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

Upvotes: 0

Related Questions