Shutting down and reconnecting a socket - How to avoid a long wait?

I am working with a socket in python, and while at the development stage, I need to kill and restart my program often.

The problem is that once I killed my python script, I have to wait a long time to restore the response socket. Here is a snippet to reproduce the problem:

#!/usr/bin/env python3                                                          

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 4321))
try:
    s.listen(5)
    while True:
        (a, b) = s.accept()
        print(a.recv(1000))
except KeyboardInterrupt:
    print("Closing")
    s.shutdown(socket.SHUT_RDWR)
    s.close()

Pressing Cz launches the exclusive code, calling the functions shutdownand close, but I cannot restart my program before the socket timeout (GNU / Linux environment).

How can i avoid this?

+3
source share
1 answer

I'm not sure how to do this in Python, but you want to set the SO_REUSEADDR option.

+4

Source: https://habr.com/ru/post/1734778/


All Articles