问题
I have an issue very similar to jbu's bind errors in Java.
The difference is that my server opens a stream to accept connections all day, then I have a script to hard kill the service in the morning, wait 10 secs, then restart the service to accept connections. Most of the time, it works, but on occasion, the service will suffer BindExceptions when attempting to start up. I can't think of a good way to close the stream in the program before it's hard killed by an external script, so I wanted to know what would be a good way to release the locks on the ports, either externally, or if I should rearchitect the design so that the service kills itself, but ensures that all connections are closed before doing so. (I'm running Windows Server 2008 on the machine.)
回答1:
When a TCP connection is closed the connection may remain in a timeout state for a period of time after the connection is closed (typically known as the TIME_WAIT state or 2MSL wait state). For applications using a well known socket address or port it may not be possible to bind a socket to the required SocketAddress if there is a connection in the timeout state involving the socket address or port.
That's why You notice that sometimes the service will suffer BindExceptions even though you have wait for 10 Seconds.
Enabling SO_REUSEADDR prior to binding the socket using bind(SocketAddress) allows the socket to be bound even though a previous connection is in a timeout state. This can be achieved using:
ServerSocket.setReuseAddress(true) prior to binding the socket.
This enforces or conveys the OS to reuse the same address even if it is already showing as binded...
来源:https://stackoverflow.com/questions/15140588/java-server-not-releasing-connection-lock