问题
In my Python socket program, I sometimes need to interrupt it with Ctrl-C. When I do this, it does close the connection using socket.close().
However, when I try to reopen it I have to wait what seems like a minute before I can connect again. How does one correctly close a socket? Or is this intended?
回答1:
Yes, it is intended. Here you can read detailed explanation. It is possible to override this behavior by setting SO_REUSEADDR option on a socket. For example:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
回答2:
$ ps -fA | grep python
501 81211 12368 0 10:11PM ttys000 0:03.12
python -m SimpleHTTPServer
$ kill 81211
回答3:
If you use a TCPServer, UDPServer or their subclasses in the SocketServer module, you can set this class variable (before instanciating a server):
SocketServer.TCPServer.allow_reuse_address = True
(via SocketServer.ThreadingTCPServer - Cannot bind to address after program restart )
This causes the init (constructor) to:
if self.allow_reuse_address:
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
回答4:
A simple solution that worked for me is to close the Terminal and restart it.
回答5:
because you trying to run service in same port that is already running.
some time its happen because your service is not stopped in process stack. you have to kill them
no need to install anything here is the one line command to kill all running python processes.
for Linux based OS:
Bash:
kill -9 $(ps -A | grep python | awk '{print $1}')
Fish:
kill -9 (ps -A | grep python | awk '{print $1}')
回答6:
Nothing worked for me except running a subprocess with this command, before calling HTTPServer(('', 443), myHandler):
kill -9 $(lsof -ti tcp:443)
Of course this is only for linux-like OS!
回答7:
Got the same error :
Steps followed :
1 - used $ ps -fA | grep python
2 - Killed all the process
3 - Closed terminal
4 - relaunced and launched the application ( mkchromecast).
5 - did not get this error message.
Got another issue.
following up on that .
来源:https://stackoverflow.com/questions/4465959/python-errno-98-address-already-in-use