Python服务器“每个套接字地址通常只允许使用一次”

2024-04-26 08:07:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python创建一个非常基本的服务器,它监听端口,在客户端尝试连接时创建TCP连接,接收数据,发送回某些内容,然后再次监听(并无限期地重复该过程)。这就是我到目前为止所做的:

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”)。但我在最后几分钟关闭服务器后尝试启动服务器时,偶尔会收到以下错误消息:

Traceback (most recent call last):
  File "path\server.py", line 8, in <module>
    s.bind((serverName, serverPort))
  File "C:\Python27\lib\socket.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

我正在使用Windows7用python编程。有没有办法解决这个问题


Tags: 服务器localhosthelloworldsizeisbindbuffer
3条回答

在@JohnKugelman发布的the article中指出,即使在启用SO_REUSEADDR之后,您也不能像以前那样使用套接字连接到同一个远程端:

SO_REUSADDR permits you to use a port that is stuck in TIME_WAIT, but you still can not use that port to establish a connection to the last place it connected to.

我知道你只是在测试/玩玩。但是,要避免此错误,您确实需要确保正确终止连接。您还可能搞乱操作系统的tcp计时:http://www.linuxquestions.org/questions/linux-networking-3/decrease-time_wait-558399/

出于测试目的,如果您只是以循环方式更改serverPort也可以,您认为如何

在Windows上,您可以尝试以下步骤:

一,。检查哪个进程使用该端口

# 4444 is your port number
netstat -ano|findstr 4444

你会得到这样的结果:

# 19088 is the PID of the process
TCP    0.0.0.0:4444           *:*                                    19088

二,。终止这个过程

与:

tskill 19088

或:

taskkill /F /PID 19088

祝你好运

在调用bind()之前启用SO_REUSEADDR套接字选项。这允许立即重用地址/端口,而不是将其停留在时间等待状态几分钟,等待延迟的数据包到达

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

相关问题 更多 >