3
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?

2
  • Why do you need two ports? Commented Apr 25, 2015 at 11:48
  • @EJP The buyer and seller (separate programs) will connect through different ports and they can send different type of commands so I have to separate the ports to differentiate them. Commented Apr 25, 2015 at 12:03

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Also not the only way.
Ya. We can solve with multi-threading, the same we can achieve with Single thread using NIO.
0

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

5 Comments

Not the only way. You can also use a NIO Selector. But certainly the simplest way.
Sorry, I meant that this was the only way using a ServerSocket from the java.net package. I haven't looked into NIO server stuff yet
Thanks, I created a Thread for reading each port and it worked but it throws BindException like 10 times for each connect, but it still runs correctly so I guess I just have to ignore the BindExceptions
I'm not 100% sure about bind exceptions, but I think that means that the port is already occupied
I moved the buyerSocket and sellerSocket outside the while loop of Thread and it solved the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.