【发布时间】:2012-09-11 03:56:38
【问题描述】:
我正在尝试在 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
我正在使用 Windows 7 在 python 中编程。关于如何解决这个问题的任何想法?
【问题讨论】:
-
像twisted 这样的高级模块比直接使用套接字更有效率。
-
@PauloScardine:是的,但这是我正在做的一个练习,我需要使用套接字(以了解有关低级内容的更多信息)。
-
@PauloScardine 顺便说一句,我在 Windows 上使用 Twisted 时也遇到了这个错误
标签: python sockets connection webserver