I have the following code in my main function:
def main():
server = socket.socket();
server.bind((address, port))
server.listen(1)
sock, addr = server.accept()
try:
while True:
message = sock.recv(buffer_size)
# Do some stuff...
sock.send(answer)
except KeyboardInterrupt:
pass
finally:
sock.close()
server.close()
The program runs completely fine, and everything works perfectly, until I decide to end it.
I end my program using Ctrl-C
(or ^C
). The KeyboardInterrupt
exception is getting handled properly and the finally block IS reached, however for some reason when I run the program again, I get an OSError
about the port being in use, and I have to wait about 1 minute until the socket gets closed before I can re-run the code. I am on Linux if that matters.
What am I missing here? Why isn't the socket closed properly?
EDIT: This is not a duplicate of How to close a socket left open by a killed program? because in my case the socket was gracefully closed, as opposed to that question.