python失败后如何关闭socket?

2024-10-01 15:47:05 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,我遇到了Python中的套接字,并面临这样的问题:当Python代码中发生错误时,例如第二个脚本启动端口上的conn.close()之前的语法错误。脚本已经完成,但是套接字仍然打开,有点像繁忙的套接字。在

以下是一个错误示例:

web@web-X501A1 /var/www $ cd /home/web/www/public/py
web@web-X501A1 ~/www/public/py $ python sockets.py
connected: ('127.0.0.1', 47168)
Traceback (most recent call last):
  File "sockets.py", line 164, in <module>
    data = re.find('(<onvif>.*<\/onvif>)')
AttributeError: 'module' object has no attribute 'find'
web@web-X501A1 ~/www/public/py $ python sockets.py
Traceback (most recent call last):
  File "sockets.py", line 154, in <module>
    sock.bind(('', 9090))
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
web@web-X501A1 ~/www/public/py $ python sockets.py
Traceback (most recent call last):
  File "sockets.py", line 154, in <module>
    sock.bind(('', 9090))
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use

代码:

^{pr2}$

Tags: inpywebmostwwwlinesocketpublic
3条回答

如果您使用netstat -nutap,您应该注意到您的连接似乎仍然处于启动状态,处于一个名为TIME_WAIT的状态。在

这是TCP协议的一部分,根据wikipedia

represents waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request. [According to RFC 793 a connection can stay in TIME-WAIT for a maximum of four minutes known as a MSL (maximum segment lifetime).]

因此,当您尝试立即重新连接到同一个端口时,python会抱怨该端口仍然很忙,无法绑定,并说:

socket.error: [Errno 98] Address already in use

请参阅this旧问题,其中询问如何避免等待时间。在

在try/finally子句中包含套接字的用法。关闭finally部分中的套接字。可能在except部分中处理异常。与此类似:

try:
    result = x / y
except ZeroDivisionError:
    print "division by zero!"
else:
    print "result is", result
finally:
    print "executing finally clause"

这里的问题是在没有正确的TCP连接关闭序列的情况下脚本崩溃时发生的脏套接字关闭。谢天谢地,有一个简单的解决方案告诉内核忽略套接字已经在使用(它绑定到的端口):

sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

就这样,在bind调用之前加上这个,就可以设置了。调试完其他错误后,调试将更简单、更省时;)请参阅文档https://docs.python.org/2/library/socket.html#socket.socket.setsockopt

相关问题 更多 >

    热门问题