gpt4 book ai didi

python - 关闭没有 socket.close() 的 UDP 套接字

转载 作者:太空狗 更新时间:2023-10-30 03:04:47 24 4
gpt4 key购买 nike

有一个打开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将在 block 完成或程序退出时关闭套接字。

关于python - 关闭没有 socket.close() 的 UDP 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14423563/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com