2012-02-26 56 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