簡體   English   中英

Python HTTP服務器在一段時間后給出錯誤

[英]Python HTTP server giving error some time after

我對Python HTTP服務器進行了如下編碼,並從該python文件所在的目錄運行該服務器。 我在cmd中鍵入“ python myserver.py”,服務器成功啟動並讀取目錄中的index.html,但是我的問題是一段時間后,我的代碼給出以下錯誤並關閉了服務器

追溯(最近一次呼叫最近):requesting_file = string_list [1]中的文件“ myserver.py”,第20行,IndexError:列表索引超出范圍

我該如何解決這個問題?

import socket

HOST,PORT = '127.0.0.1',8082

my_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
my_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
my_socket.bind((HOST,PORT))
my_socket.listen(1)

print('Serving on port ',PORT)

while True:
    connection,address = my_socket.accept()
    request = connection.recv(1024).decode('utf-8')
    string_list = request.split(' ')     # Split request from spaces

    print (request)

    method = string_list[0]
    requesting_file = string_list[1]

    print('Client request ',requesting_file)

    myfile = requesting_file.split('?')[0] # After the "?" symbol not relevent here
    myfile = myfile.lstrip('/')
    if(myfile == ''):
        myfile = 'index.html'    # Load index file as default

    try:
        file = open(myfile,'rb') # open file , r => read , b => byte format
        response = file.read()
        file.close()

        header = 'HTTP/1.1 200 OK\n'

        if(myfile.endswith(".jpg")):
            mimetype = 'image/jpg'
        elif(myfile.endswith(".css")):
            mimetype = 'text/css'
        else:
            mimetype = 'text/html'

        header += 'Content-Type: '+str(mimetype)+'\n\n'

    except Exception as e:
        header = 'HTTP/1.1 404 Not Found\n\n'
        response = '<html><body><center><h3>Error 404: File not found</h3><p>Python HTTP Server</p></center></body></html>'.encode('utf-8')

    final_response = header.encode('utf-8')
    final_response += response
    connection.send(final_response)
    connection.close()

不保證socket.recv(n)讀取消息的整個n個字節,並且在某些情況下返回的字節數可能少於請求的字節數。

關於您的代碼,有可能僅接收到method或其一部分,而接收到的數據中沒有任何空格字符。 在這種情況下, split()將返回一個包含一個元素的列表,而不是您假設的兩個元素。

解決方案是檢查是否已收到完整消息。 您可以通過循環直到收到足夠的數據來做到這一點,例如,可以通過檢查數據長度並循環直到達到最小值來確保已接收到一些最小字節數。

或者,您可以繼續閱讀,直到收到新行或其他一些前哨字符。 最好限制傳入數據的長度,以避免服務器被流氓客戶端的數據淹沒。

最后,檢查split()是否返回您期望的兩個值,如果沒有,則進行相應的處理。 此外,請注意文件名; 如果它包含相對路徑,例如../../etc/passwd怎么../../etc/passwd

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM