在程序终止的情况下如何关闭端口? [英] How do I close a port in a case of program termination?

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

问题描述

我在我的一个 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.

您可以使用 ServerSocket.setReuseAddress(true) 方法.

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

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

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