简单的Web服务器在运行时挂起

时间:2012-02-26 19:45:03

标签: python multithreading sockets

对于一些工作,我创建了一个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()

干杯

1 个答案:

答案 0 :(得分:1)

您是使用Python 2而不是Python 3运行示例吗?在Python 2 socket.makefile中没有buffering关键字参数。你的例子在Python 3中适合我。