2012-02-26 57 views
0

对于工作而言,我创建了一个web服务器,它可以通过线程处理多个请求,但是当我运行该程序时它会挂起,我不能解决原因。它从未达到印刷的阶段('通过'连接',地址)。任何帮助和探索将不胜感激。简单的Web服务器运行挂起

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() 

干杯

+0

说“对不起,如果缩进有点乱了”可能会弄乱您的Python程序以及';)'。 – 2012-02-26 19:47:26

+3

...你正在写** Python **。请修复缩进。 – Amber 2012-02-26 19:47:43

+0

这应该是现在 – EmberZ 2012-02-26 19:52:32

回答

1

是否运行与Python 2而不是Python 3里你的榜样?在Python 2中socket.makefile没有buffering关键字参数。您的示例在Python 3中适用于我。

+0

我曾尝试使用pydev与eclipse 2.7.2和3.2.2,既不显示打印消息,只是挂起。 – EmberZ 2012-02-26 20:15:13

+0

啊,Eclipse可能是你的问题。尝试使用Python 3.x在Eclipse之外运行它。 – zeekay 2012-02-26 20:18:43

+0

通过python命令行运行时仍然没有得到任何结果。这个问题似乎发生在connection,address = s.accept()之前,这个点将被打印。 – EmberZ 2012-02-26 20:22:08