简体   繁体   English

Python Web服务器-拆分文件名时出现IndexError

[英]Python web server - IndexError when splitting filename

I have successfully been able to access my web-server from a browser, downloaded a file on the server and properly viewed it with chrome. 我已经能够从浏览器成功访问我的Web服务器,在服务器上下载了文件,并使用chrome对其进行了正确查看。 However, when the server standbys for approx. 但是,当服务器待机约 20 seconds, it'll crash with an IndexError. 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)

The output i get is the following: 我得到的输出如下:

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

This is probably the client closing the connection. 这可能是客户端关闭连接。 When the connection is finished, an empty string '' is received. 连接完成后,将收到一个空字符串''

''.split()[1] will fail with index out of range . ''.split()[1]将失败, index out of range My advice is to try with this patch: 我的建议是尝试使用此修补程序:

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

As an aside, you should recv from your socket until you get the empty string. recv ,您应该从套接字中恢复,直到获得空字符串。 In your code, what happens if the request is larger than 1024 ? 在您的代码中,如果请求大于1024会发生什么? Something like this can be done: 可以这样做:

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()

You should read Socket Programming HOWTO , specially the part of creating multithreaded servers, which is probably how you want to do yours :) 您应该阅读Socket Programming HOWTO ,特别是创建多线程服务器的部分,这可能是您想做的事情:)

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM