java 释放连接,Java服务器未释放连接锁定

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.)

解决方案

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...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值