没有使用socket.close()如何关闭UDP套接字

5

有一个打开 UDP 套接字的 Python 程序

receiveSock = socket(AF_INET, SOCK_DGRAM)
receiveSock.bind(("", portReceive))

有时程序会在运行时失败或被终止,导致它无法达到预期的目标。
receiveSock.close()

这样,下次运行该程序时,我就可以得到
receiveSock.bind(("",portReceive))
  File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use

我该如何使用shell命令(或其他有用的方法)关闭此套接字?
1个回答

4
您有两个选择:
try:
   # your socket operations
finally:
   # close your socket

或者,对于更新版本的Python:

with open_the_socket() as the_socket:
   # do stuff with the_socket

with 语句 在代码块执行完毕或程序退出时会自动关闭 socket。


我考虑过使用 finally,但在中断关闭(crl+Z)时它不会进入到那个 finally - URL87
1
在UNIX/Linux中,CTRL+Z会暂停任务,因此您不应该期望套接字被关闭。 - Burhan Khalid
CTRL+C 也不会进入 finally 块。 - URL87
2
@URL87 什么意思?它确实可以。如果不能,请检查你的信号处理过滤器(父shell)和你的假设。证明:http://pastebin.com/iY8LQDyK - sehe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接