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 命令(或任何其他有用的想法)关闭此套接字?

4

1 回答 1

4

你有两个选择:

try:
   # your socket operations
finally:
   # close your socket

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

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

with statement块完成或程序退出时,将关闭套接字。

于 2013-01-20T10:48:49.910 回答