Java服务器未释放连接锁定 [英] Java Server Not Releasing Connection Lock
问题描述
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.)
推荐答案
当TCP连接关闭时,连接可能会在连接关闭后的一段时间内保持超时状态(通常称为TIME_WAIT状态或2MSL)等待状态).对于使用众所周知的套接字地址或端口的应用程序,如果在超时状态下存在涉及套接字地址或端口的连接,则可能无法将套接字绑定到所需的SocketAddress.
因此,您注意到有时即使您等待10秒,该服务也会遭受BindExceptions.
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.
在使用bind(SocketAddress)绑定套接字之前启用SO_REUSEADDR,即使先前的连接处于超时状态,也可以绑定套接字. 可以使用以下方法实现:
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) ,然后再绑定套接字.
即使操作系统已经显示为已绑定,这也可以强制或传达OS重用相同的地址.
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...
这篇关于Java服务器未释放连接锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!