【问题标题】:IndexError: list index out of range Multi-threaded serverIndexError:列表索引超出范围多线程服务器
【发布时间】:2017-03-05 16:19:12
【问题描述】:
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

【问题讨论】:

  • 我建议使用pdb 来查看发生索引错误时message 是什么。任何时候你得到超过 1024 长度的输入而没有任何空格,你都会得到这个错误。

标签: python multithreading tcp server


【解决方案1】:

如果由于还没有数据而没有从套接字接收任何内容,split() 将返回 [''] 并仅包含 on 项,而其上的 [1] 将失败。

尝试在失败的行之前添加这个

if not message:
    # time.sleep(0.01)
    continue

sleep() 调用将防止线程使用过多的 CPU,您可以取消注释并根据需要调整值。

【讨论】:

    猜你喜欢
    • 2011-10-31
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多