Java服务器未释放连接锁定 [英] Java Server Not Releasing Connection Lock

查看:145
本文介绍了Java服务器未释放连接锁定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常类似于区别在于我的服务器整天打开一个流以接受连接,然后我有一个脚本在早上强行终止该服务,等待10秒,然后重新启动该服务以接受连接.在大多数情况下,它可以工作,但是有时,服务在尝试启动时会遇到BindExceptions.我想不出一种在被外部脚本硬杀死之前关闭程序中流的好方法,所以我想知道什么是释放端口上的锁的好方法,无论是在外部还是在我应该重新设计设计,以使服务自行终止,但确保在这样做之前关闭所有连接. (我正在计算机上运行Windows Server 2008.)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆