1

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.

Peter
  • 3,186
  • 3
  • 26
  • 59
  • IDLE encapsulates a Python runtime and puts debug hooks around what you're executing so it doesn't really kill your scripts when you tell it to quit. Either use a more competent IDE (pretty much any IDE out there is more competent than IDLE) that is able to really kill the environment on demand or run your scripts manually when testing. Once the Python interpreter running your script is killed the port will most likely be released, and besides you'll be able to capture any exception and deal with it accordingly. – zwer Dec 16 '17 at 15:55
  • This seems to be a duplicate of [this question](https://stackoverflow.com/questions/5875177/how-to-close-a-socket-left-open-by-a-killed-program). – bnaecker Dec 16 '17 at 16:44
  • Type a section that will find and destroy the previous app at the beginning of your application. Also never forget to use try-except. – dsgdfg Dec 16 '17 at 17:14
  • I only use IDLE as it's super quick to test (I keep meaning to upgrade but never do), but yeah, it appears you're correct in the port appearing to be released straight away when running it from the console, thanks. On dsgdfg's suggestion ,I found how to kill any program using a particular port, so I may add that in for if the initial server start fails :) – Peter Dec 16 '17 at 18:19
  • 1
    Terminating the old program if it's bound to the port works great thanks. I also found it's possible to bind to port 0 and it'll randomly select one. – Peter Dec 16 '17 at 18:57

0 Answers0