Python 简单web服务器在运行时挂起
为了完成一系列的工作,我创建了一个web服务器,它可以通过线程处理多个请求,但是现在当我运行程序时它会挂起,我就是不知道为什么。它永远不会到达打印阶段(“连接方式”,地址)。任何帮助和解释都将不胜感激Python 简单web服务器在运行时挂起,python,multithreading,sockets,Python,Multithreading,Sockets,为了完成一系列的工作,我创建了一个web服务器,它可以通过线程处理多个请求,但是现在当我运行程序时它会挂起,我就是不知道为什么。它永远不会到达打印阶段(“连接方式”,地址)。任何帮助和解释都将不胜感激 class Connect(threading.Thread): def __init__ (self, connection): self.clientsocket = connection threading.Thread.__init__(self) def run(se
class Connect(threading.Thread):
def __init__ (self, connection):
self.clientsocket = connection
threading.Thread.__init__(self)
def run(self):
stream = connection.makefile(mode="rw", buffering=1, encoding="utf-8")
firstLine = stream.readline().split(" ")
hList = []
method = firstLine[0]
path = firstLine[1]
line = stream.readline().strip()
while line != "":
hList.append(line.split(":", 1))
line = stream.readline().strip()
if method != 'GET':
stream.write("HTTP/1.0 405 Unsupported\n\nUnsupported")
else:
stream.write("HTTP/1.0 200 Success\n")
stream.write("Content-type: text/plain\n")
stream.write("\n")
stream.write(str(firstLine) + '\n')
for header in hList:
stream.write(str(header) + "\n")
stream.close()
connection.close()
return path == "/stop"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 9999))
s.listen(1)
while 1:
connection, address = s.accept()
print('Connected by', address),
Connect(connection).start()
干杯您是否使用Python 2而不是Python 3运行示例?在Python 2中,
socket.makefile
没有缓冲
关键字参数。您的示例在Python 3中非常适合我。说“如果缩进有点混乱,请道歉”也可能会弄乱您的Python程序;)代码>…您正在编写Python。请修复缩进。那应该是现在。我已经尝试在pydev和eclipse上同时使用2.7.2和3.2.2,既不显示打印消息也只是挂起。啊,eclipse可能是你的问题。尝试使用Python 3.x在Eclipse之外运行它。通过Python命令行运行它时仍然没有得到任何结果。问题似乎发生在连接处,address=s.accept(),因为此时之前的任何内容都将被打印。您在哪个平台/操作系统上?在OSX/Linux上似乎工作得很好。好吧,它肯定是Python 3代码,不会与Python 2.7一起工作。我可以验证它在OSX和Linux上是否可以与Python 3.2.2一起工作。你一定忽略了什么。