关闭后端口是否应该立即可用? [英] Should ports be available immediately after closing?

查看:42
本文介绍了关闭后端口是否应该立即可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在用 Python 在两个客户端和一个服务器之间编写一个简单的 TCP/IP 服务器.目前,当我尝试在同一端口关闭后立即重新运行该程序时,shell 会通知我该端口正忙.

I've been writing a simple TCP/IP Server in Python between two clients and a server. Currently, when I try to rerun the program immediately after it closes on the same port, the shell is informing me that the port is busy.

我认为这应该表明某处没有正确关闭连接,但我似乎找不到任何挥之不去的套接字.

I think that this should indicate that somehow not properly closing a connection somewhere but I can't seem to find any lingering sockets.

我的问题是,这个假设正确吗?我是打开一个套接字还是这种行为是正常的?如果是这样,有人对我如何找到它有任何建议吗?

My question is, is this assumption correct? Am I leaving open a socket or is this behavior otherwise normal? If so, does anyone have any advice as to how I could go about finding it?

在服务器端,我打开两个连接并将它们放入一个元组中,这样我就可以循环遍历它们:

On the server side, I open two connections and put them into a tuple so I can cycle through them with a loop:

    (self.con1, rec1) = self.s.accept()
    (self.con2, rec2) = self.s.accept()
    self.con = (self.con1, self.con2)

以下代码是否足以关闭这些连接?

Would the following be sufficient code to close these connections?

    self.con1.close()
    self.con2.close()

是否有可能将连接放入元组中会创建可能存在的连接的新副本?

Could it be possible that maybe putting the connections into the tuple is creating a new copy of connections that are maybe lingering?

推荐答案

这是正常的.TCP 为持续几分钟(最大段生存时间的两倍)的端口定义了 TIME_WAIT 状态,在此期间它们不能被重复使用.这是一种数据完整性措施.您可以通过在绑定套接字之前设置 SO_REUSEADDR 选项来克服它.

It's normal. TCP defines a TIME_WAIT state for ports that last for a few minutes (twice the Maximum Segment Lifetime), during which they can't be re-used. It's a data integrity measure. You can overcome it by setting the SO_REUSEADDR option before binding the socket.

这篇关于关闭后端口是否应该立即可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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