• Post Reply Bookmark Topic Watch Topic
  • New Topic

Address already in use

 
Frank Bush
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have written a multithreaded server using sockets.

Now, I try to simulate heavy load in order to test synchronization issues. The simulation launches multiple threads that connect to the server and issue a few commands. The servers as well as the clients all run on the same machine (Windows XP). From time to time, an "address already in use" IO exception is thrown by the following statement:



Sockets and input / output streams are properly closed on both ends.

I am wondering if there is something wrong with my code, or if it is a limitation of the OS. I would greatly appreciate any advice.

Thanks,
Frank
 
tommy k. lee
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Socket socket = new Socket(host,port);

If the port is already in use when this code is executed, an exception will be thrown. Since you have the client and server on the same machine, the client may be binding to ports that the server is trying to use.

When a client initiates a connection to the server, it will bind to an ephemeral / transient port as its source port. If the client happens to bind to a source port that the server needs, the server will not be able to bind to that port.

An easy fix is to separate the client and server onto separate machines, so there is no port contention.
 
peter wooster
Ranch Hand
Posts: 1033
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by tommy k. lee:
Socket socket = new Socket(host,port);

If the port is already in use when this code is executed, an exception will be thrown. Since you have the client and server on the same machine, the client may be binding to ports that the server is trying to use.

When a client initiates a connection to the server, it will bind to an ephemeral / transient port as its source port. If the client happens to bind to a source port that the server needs, the server will not be able to bind to that port.

An easy fix is to separate the client and server onto separate machines, so there is no port contention.


I don't think this is the OP's problem. The ports used by the server will not be used by the client as the system will chose an ephemeral port to bind to. I'd suggest that the OP check the state of the ports on their system when this occurs using netstat -a. If a lot of them are stuck in TIME_WAIT there is a problem with closing connections.

Using setReuseAddress(true) will allow the socket to connect to a port that's in TIME_WAIT. This is not a good fix, but if it fixes the problem, it indicates where the trouble is.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!