Python服务器“通常只允许每个套接字地址使用一次"
问题描述
我正在尝试在 python 中创建一个非常基本的服务器,它侦听端口,在客户端尝试连接时创建 TCP 连接,接收数据,发回某些内容,然后再次侦听(并无限期地重复该过程).这是我目前所拥有的:
I'm trying to create a very basic server in python that listens in on a port, creates a TCP connection when a client tries to connect, receives data, sends something back, then listens again (and repeats the process indefinitely). This is what I have so far:
from socket import *
serverName = "localhost"
serverPort = 4444
BUFFER_SIZE = 1024
s = socket(AF_INET, SOCK_STREAM)
s.bind((serverName, serverPort))
s.listen(1)
print "Server is ready to receive data..."
while 1:
newConnection, client = s.accept()
msg = newConnection.recv(BUFFER_SIZE)
print msg
newConnection.send("hello world")
newConnection.close()
有时这似乎工作得很好(如果我将浏览器指向localhost:4444",服务器会打印出 HTTP GET 请求,而网页会打印出文本hello world").但是当我在最后几分钟关闭服务器后尝试启动服务器时,偶尔会收到以下错误消息:
Sometimes this seems to work perfectly well (if I point my browser to "localhost:4444" the server prints out the HTTP GET request and the webpage print the text "hello world"). But I'm getting the following error message sporadically when I try to start the server after closing it in the last few minutes:
Traceback (most recent call last):
File "pathserver.py", line 8, in <module>
s.bind((serverName, serverPort))
File "C:Python27libsocket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
我正在使用 Windows 7 在 python 中编程.关于如何解决这个问题的任何想法?
I'm programming in python using Windows 7. Any ideas on how to fix this?
解决方案
启用 SO_REUSEADDR 调用 bind() 之前的套接字选项.这允许地址/端口被立即重用,而不是停留在 TIME_WAIT 状态几分钟,等待迟到的数据包到达.
Enable the SO_REUSEADDR socket option before calling bind(). This allows the address/port to be reused immediately instead of it being stuck in the TIME_WAIT state for several minutes, waiting for late packets to arrive.
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
相关文章