How to close socket connection on Ctrl-C in a python programme

南笙酒味 提交于 2019-11-30 18:35:15

As per the docs the error OSError: [Errno 48] Address already in use occurs because the previous execution of your script has left the socket in a TIME_WAIT state, and can’t be immediately reused. This can be resolved by using the socket.SO_REUSEADDR flag.

For eg:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))

You need to register a hook for this, something like:

#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
        # close the socket here
        sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!