I'm attempting to get a simple server up and running with sockets, where it will send out the same information to any connected client. I've successfully managed to handle threads and stopping them in the case of KeyboardInterrupt
, but I can't figure out how to close the socket if the script is ended early (such as the python process closed or you force run the script again).
A very basic example would be this:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket_process.bind(('localhost', 60000))
socket_process.listen(5)
conn, addr = socket_process.accept()
If you run that (on Windows at least), and then hit F5 to run it again, you get error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted.
. It does eventually close after half a minute or something, but I'd like it to instantly close if the script that spawned it no longer exists.
Even if a timeout is set, it doesn't cause the error to go away any time sooner.
For the record, those types of exit aren't caught by atexit
. I'm thinking something similar to the multiprocessing daemon option could work if it exists.