1
votes

I am wondering about, how I can wait a ServerSocket connection on Socket client side.

When I execute the server (send) first, it waits the client connection with the method ServerSocket.accept. The problem is that the client (receive) cannot be executed without the server has been executed first. I would like add a condition to allow the client to wait the connection from the server. Is it possible?

SEND (server)

ServerSocket servsock = new ServerSocket(1234);
Socket sock = servsock.accept();

RECEIVE (client)

Socket sock = new Socket(from, 1234);

ERROR (client)

java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
    at java.net.Socket.connect(Socket.java:529)
    at java.net.Socket.connect(Socket.java:478)
    at java.net.Socket.<init>(Socket.java:375)
    at java.net.Socket.<init>(Socket.java:189)

Thank you.

2

2 Answers

4
votes

There is no built-in way to do that. You'll have to catch the exception on the client side, and implement a retry mechanism yourself.

Pseudo-code:

Socket sock = null;
while (retryCounter < threshold) {
  try {
   retryCounter++;
   sock = new Socket(form, 1234);
  } catch (...) {
    // handle exceptions
    // possibly add a sleep period
  }
}
if (sock == null) {
  // you failed to connect
} else {
  // you're connected
}

Be careful if you have a GUI: you might need to implement some of that in a separate thread or use timers to avoid freezing your UI.

2
votes

Thank to Mat, it works.

    Socket sock = null;
    while (true) {
      try {
       sock = new Socket(from, 1234);
       if (sock != null) { break; }
       }
      catch (IOException e) { Thread.sleep(1000); }
    }
    // rest of the code