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

前端 未结 2 945
梦谈多话
梦谈多话 2021-01-04 06:17
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)

any_connection = False

while True:
    try:
        conn, addr = s.accept()
         


        
相关标签:
2条回答
  • 2021-01-04 06:52

    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))
    
    0 讨论(0)
  • 2021-01-04 06:59

    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)
    
    0 讨论(0)
提交回复
热议问题