I'm learning how to use sockets in python, and quite often when my program crashes or I Ctrl+C the server socket somehow stays listening on the port. This obviously stops the program from listening on that port when it starts back up again, so I have to keep开发者_开发问答 changing it.
I'm guessing I need to do socket.close() somewhere, but where?
You could try the atexit module.
import atexit
function close_socket:
s.close()
atexit.register(close_socket)
If the issue is delays in the port becoming available during testing, I would suggest setting SO_REUSEADDR
which will allow the port to be bound again immediately instead of waiting for timeouts on the TCP stack.
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Terminating a program makes all its sockets automatically close. However, the TCP ports are still kept in use after that. The UNIX socket FAQ has a really long explanation in section 2.7.
For testing purposes, it may be best to ask for an arbitrary port (or ask for successive ones, like 8000, 8001, 8002, ...) and output that port in the console.
精彩评论