1
votes


I am currently working on a simple multiplayer game where serveral clients need to connect to a server.

My server consits of a single serverSocket. This serverSocket accepts incoming connections and hands them over to connection object that starts a separate thread.

ServerSocket seso = new ServerSocket(12345);

while(true){
    Socket toClient = seso.accept();                
    new Connection(toClient); //creates a thread that opens streams etc
}

Clients open a new Socket and connect to this server.

Socket toServer = new Socket();
toServer.setReuseAddress(true);
toServer.bind(new InetSocketAddress(65432)); //always using the same port   
toServer.connect(new InetSocketAddress(serverIP,12345));

Now if i close the connection to the server using toServer.close(); and try to connect again to the server, i get an "address already in use: connect" exception.

Using TCPView i can see that the state of the client procress changes to TIME_WAIT. But shouldn't i be able to use this port again because of setReuseAddress(true)? Am i using it wrong or is it an server problem?

I do always call .close() on toClient and toServer. Nevertheless i always have to wait until the socket is completely closed (after TIME_WAIT) before this client can connect again to the server.

When i close the entire application, the socket is immediately closed (not in state TIME_WAIT) and this client can connect to my server. (And ofc there is a connection reset exception in my server)

How can I do that without always closing the application ?
Thanks for your help.

1
It is unusual to insist that the client always use the same port number, or indeed to bind() the client socket before connecting at all. If you do not do so then you should not need setReuseAddress() either, and you should not see the problem you describe.John Bollinger

1 Answers

4
votes

To expand on my comment, a client / server protocol requires the server to listen on a port known to or discoverable by the client -- that can be considered the definition of "server" -- but it does not ordinarily require clients to connect from a specific port. If you do not bind the client socket to a particular port, then the underlying system will choose an available (source) port automatically and transparently.

If the server depends for some reason on clients connecting from a particular port, then you should re-evaluate that aspect of your design. If it does not, then you are making your own trouble by having clients connect that way. This should be all you need to do:

Socket toServer = new Socket();
toServer.connect(new InetSocketAddress(serverIP, 12345));