简体   繁体   English

在JAVA中如何连接并等待端口完成TIME_WAIT

[英]In JAVA how to connection and wait for port to finish TIME_WAIT

I have a part in code that checks port availability (opens connection and immediately close it) : 我在代码中有一部分检查端口可用性(打开连接并立即关闭它):

try{
   new ServerSocket(currentConnector.getPort()).close();
 }

The porblem here is that the port enters a state of TIME_WAIT which differs from system to system. 这里的问题是端口进入的TIME_WAIT状态因系统而异。 I want to make sure that after close() the port is available. 我想确保在close()该端口可用。

One way I can think of is adding 60-90 seconds of sleep. 我能想到的一种方法是增加60-90秒的睡眠时间。 But it doesn't seem very elegant. 但这似乎并不优雅。

Can I validate with Java (w/o bash/batch) that the port was released from TIME_WAIT? 我可以使用Java(不带bash / batch)验证端口是从TIME_WAIT释放的吗?

Thanks! 谢谢!

  1. The port only enters TIME-WAIT if someone has connected to it. 仅当有人连接到端口时,该端口才进入TIME-WAIT。

  2. You can overcome the BindException that results by: 您可以通过以下方法克服BindException

     ServerSocket ss = new ServerSocket(); ss.setReuseAddress(true); ss.bind(new InetSocketAddress(port)); 
  3. However I question the objective. 但是我对目标提出了质疑。 If you want to listen at the port, listen at it, and catch the exception then. 如果要监听端口,请监听该端口,然后捕获异常。 If you want to see whether you can connect to it, connect to it, and handle the exception as it arises. 如果要查看是否可以连接到它,请连接到它,并在出现异常时进行处理。 The technique of trying to predict the future is just fortune-telling in the end. 最终预测未来的技术只是算命。 Unsound technique. 不完善的技术。 The correct way to detect whether any resource is available for use is just to try to use it in the normal way. 检测任何资源是否可用的正确方法只是尝试以常规方式使用它。 Anything else is liable to false negatives, false positives, and timing-window problems. 其他任何事情都有可能导致误报,误报和时序窗口问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM