用于多个连接的简单python服务器

时间:2019-05-07 10:12:18

标签: python multithreading server

我正在设置一个简单的本地python服务器,这是我的代码,但是一次只能处理一个连接。如何使其接受多个连接?

更改参数serverSocket.listen()无效

serverSocket = socket(AF_INET, SOCK_STREAM)
serverPort = 6789
print 'hostname is: ', gethostname()
serverSocket.bind(('192.168.0.103', serverPort))
serverSocket.listen(1)
while True:
     print 'Ready to serve...'
     connectionSocket, addr = serverSocket.accept()
     try:
    message =  connectionSocket.recv(1024)
    print 'Message is: ', message
    filename = message.split()[1]
    print 'File name is: ', filename
    f = open(filename[1:])
    outputdata = f.read()
    connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")
    for i in range(0, len(outputdata)):
        connectionSocket.send(outputdata[i])
    connectionSocket.send("\r\n")
    connectionSocket.close()
except IOError:
    connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n")
    connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n")
    connectionSocket.close()
 serverSocket.close()

0 个答案:

没有答案