I'm working with socket in python, and being in development stage I need to kill and restart my program frequently.
The issue is that once killed my python script, I've to wait long time to be able to rebind the listen socket. Here's 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()
Hitting C-z runs the except code, calling shutdown
and close
functions, but I'm not able to restart my program until the socket timeout (GNU/Linux environment).
How can I avoid this?