具有打开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命令(或任何其他有用的想法)关闭这个套接字?
最佳答案
你有两个选择:
try:
# your socket operations
finally:
# close your socket
或者,对于较新版本的python:
with open_the_socket() as the_socket:
# do stuff with the_socket
当块完成或程序退出时,
with statement
将关闭套接字。