from socket import *
import thread
def thread_handler(connectionSocket, addr):
while True:
# Establish the connection
print ("Ready to serve...")
# connectionSocket, addr = serverSocket.accept()
try:
message = connectionSocket.recv(1024)
# print(message, '::', message.split()[0], ":", message.split()[1])
filename = message.split()[1]
# print(filename, "||", filename[1:])
f = open(filename[1:], "r")
outputdata = f.read()
# print(outputdata)
#Send one HTTP header line into socket
#Fill in start
connectionSocket.send('\nHTTP/1.1 200 OK\n\n')
connectionSocket.send(outputdata)
#Fill in end
#Send the content of the requested file to the client
for i in range(0,len(outputdata)):
connectionSocket.send(outputdata[i:i+1])
connectionSocket.send(b'\r\n\r\n')
except IOError:
#Send response message for file not found
#Fill in Start
connectionSocket.send('\nHTTP/1.1 404 Not Found\n\n')
#Fill in end
#Close client socket
if __name__ == '__main__':
serverSocket = socket(AF_INET, SOCK_STREAM)
# Prepare a sever socket
serverSocket.bind(("localhost", 6789))
serverSocket.listen(1)
while True:
print('waiting for connection...')
connectionSocket, addr = serverSocket.accept()
print('...connected from:', addr)
thread.start_new_thread(thread_handler, (connectionSocket, addr))
serverSocket.close()
我理解多线程现在如何工作,但我无法弄清楚如何构建连接。 我试图做一个多线程版本的TCP服务器。但是,它不断给出"列表索引超出范围":
Ready to serve...
Unhandled exception in thread started by <function thread_handler at 0x10b9750c8>
Traceback (most recent call last):
File "http_server_multi.py", line 16, in thread_handler
filename = message.split()[1]
IndexError: list index out of range
答案 0 :(得分:0)
如果没有收到任何数据,因为还没有数据,split()
将只返回['']
项目,而[1]
将会失败。
尝试在失败的行之前添加此内容
if not message:
# time.sleep(0.01)
continue
sleep()
调用将阻止线程使用过多的CPU,您可以根据需要调整它并调整其值。