Python Web服务器 - 分配文件名时indexError



我已经成功地从浏览器访问了我的网络服务器,在服务器上下载了一个文件,并使用Chrome正确查看了它。但是,当服务器待机大约时。20秒,它会用indexError崩溃。

from socket import *
serverport = 972
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverport))
serverSocket.listen(1)
print 'Standing by...'
while True:
    #Establish the connection
    connectionSocket, addr = serverSocket.accept()
    try:
        message = connectionSocket.recv(1024)
        filename = message.split()[1]
        f = open(filename[1:])
        outputdata = f.read()
        for i in range(0, len(outputdata)):
            connectionSocket.send(outputdata[i])
        print 'Success! File sent!'
        connectionSocket.close()
    except IOError:
        errormessage = 'Error 404 - File not found'
        connectionSocket.send(errormessage)

我得到的输出如下:

Standing by..
Success! File sent! #sent everytime i request the webpage on the client localhost:80/helloworld.html
Traceback (most recent call last):
  File "C:/Users/Nikolai/Dropbox/NTNU/KTN/WebServer/TCPServer.py", line 14, in <module>
    filename = message.split()[1]
IndexError: list index out of range

这可能是客户关闭连接的客户端。连接完成后,收到一个空字符串''

''.split()[1]将使用index out of range失败。我的建议是尝试此补丁:

message = connectionSocket.recv(1024)
if not message:
    # do something like return o continue

顺便说一句,您应该从套接字中 recv,直到获得空字符串为止。在您的代码中,如果请求大于1024,会发生什么?这样的事情可以完成:

try:
    message = ''
    rec = connectionSocket.recv(1024)
    while rec:
        rec = connectionSocket.recv(1024)
        message += rec
    if not message:
        connectionSocket.close()            
        continue
    filename = message.split()[1]
    f = open(filename[1:])
    outputdata = f.read()
    for i in range(0, len(outputdata)):
        connectionSocket.send(outputdata[i])
    print 'Success! File sent!'
    connectionSocket.close()

您应该读取套接字编程howto,特别是创建多线程服务器的一部分,这可能是您想做的方式:)

希望这会有所帮助!

最新更新