如果程序终止,如何关闭端口? [英] How do I close a port in a case of program termination?

查看:280
本文介绍了如果程序终止,如何关闭端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的一个Java应用程序中使用Socket通信。我知道如果程序遇到任何异常终止,监听端口不会关闭,程序无法启动,因为它报告端口已经打开..
我还有办法解决这个问题吗?用于处理此问题的一般方法是什么?

I am using Socket communication in one of my Java applications.As I know if the program meets any abnormal termination the listening ports does not get closed and the program cannot be started back because it reports "Port already open.." Do I have anyway to handle this problem? What is the general way used to handle this matter?

推荐答案

听起来你的程序正在监听套接字。通常,当程序退出操作系统时,会关闭所有可能打开的套接字(包括监听套接字)。但是,对于侦听套接字,操作系统通常会在程序退出后保留端口一段时间(几分钟),以便它可以处理任何未完成的连接尝试。您可能会注意到,如果您异常关闭程序,那么回来一段时间它会启动就好了。

It sounds like your program is listening on a socket. Normally, when your program exits the OS closes all sockets that might be open (including listening sockets). However, for listening sockets the OS normally reserves the port for some time (several minutes) after your program exits so it can handle any outstanding connection attempts. You may notice that if you shut down your program abnormally, then come back some time later it will start up just fine.

如果你想避免这个延迟时间,你可以可以使用 setsockopt()来配置带有SO_REUSEADDR选项的套接字。这告诉操作系统您知道重用相同的地址是可以的,并且您不会遇到这个问题。

If you want to avoid this delay time, you can use setsockopt() to configure the socket with the SO_REUSEADDR option. This tells the OS that you know it's OK to reuse the same address, and you won't run into this problem.

您可以使用Java在Java中设置此选项 ServerSocket.setReuseAddress(true) 方法。

You can set this option in Java by using the ServerSocket.setReuseAddress(true) method.

这篇关于如果程序终止,如何关闭端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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