繁体   English   中英

python IndexError:当我尝试从字符串中获取单个字符时,字符串索引超出范围

[英]python IndexError: string index out of range when i try to get single characters from a string

我正在尝试在 python 中创建一个简单的套接字服务器,它能够为多个文件提供服务,但出现此错误:

Traceback (most recent call last):
  File "webserver.py", line 43, in <module>
    if b[x] == "G":
IndexError: string index out of range

我不明白问题是什么,因为我试图得到的角色完全在范围内,让我完全困惑。 有错误的特定部分应该从请求中获取所需的文件。 我的代码:

import sys;
import socket;

port = 80
host = socket.gethostbyname("localhost")
file = ""
file_ready = 0
x = 0
y = 0

#Create socket
print("# Creating socket")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#Bind port & host
print("# Binding to port " + str(port))
try:
    s.bind((host, port))
except socket.gaierror:
    print("# An error occured whilst binding the port\nerrorno. " + socket.errno)

#Main loop
while 1:
    #Listen for request
    print("# Now listening for incoming requests")
    s.listen(5)

    #Accept request
    conn, addr = s.accept()
    print(("# Connected with " + addr[0]))

    #Receive data from client as "b"
    b = conn.recv(1024)
    print("# Received data")

    #Decode "b", encoding = "utf-8"
    b = b.decode("utf-8")
    print("# Data decoded")

    #Request processing
    print("# Processing request")
    while 1:
        if b[x] == "G":
            x = x + 1
            if b[x] == "E":
                x = x + 1
                if b[x] == "T":
                    x = x + 1
                    if b[x] == " ":
                        x = x + 1
                        if b[x] == "/":
                            x = x + 1
                            while 1:
                                if b[x] == "/":
                                    file_ready = file_ready + 1
                                    break
                                else:
                                    file[y] = b[x]
                                    x = x + 1
                                    y = y + 1      
                            if file_ready == 1:
                                print("# Request processed")
                                break
                            else:
                                pass  
                        else:
                            x = x + 1
                    else:
                        x = x + 1
                else:
                    x = x + 1
            else:
                x = x + 1
        else:
            x = x + 1 

    #Prepare file to send to client
    print("# Preparing file")
    f = open(file, "r+")
    content = f.read()
    f.close()
    content_len = len(content)

    #Send data to the client
    conn.send('''
    HTTP/1.1 200 OK
    Server: Test
    Last-Modified: Tue, 18 Feb 2020 15:12:00 GMT
    Content-Length: ''' + content_len + '''
    Connection: close
    b\'''' + content + "'")
    print("# Data sent")

您不会在连接之间将x重置为零。

第一个连接可能工作得很好,但对于后续连接, x不在范围内。

也就是说,您可能只想使用b.split()来解析该字符串——或者更好,因为您显然正在实现一个基本的 HTTP/1.0 服务器,请使用HTTP 服务器的内置电池

不过,为了练习起见,以下是对您的代码进行的改编,适用于多个后续连接:

import socket


def handle_request(conn):
    request = conn.recv(1024).decode("utf-8")
    bits = request.split()  # Split by any runs of whitespace (non-spec-compliant but works for now)
    verb = bits[0]
    if verb == "GET":
        filename = bits[1].lstrip("/")
    else:
        conn.sendall(b"HTTP/1.1 400 Error\r\n\r\nInvalid verb")
        return

    with open(filename, "rb") as f:  # Warning: this allows reading any file on your syste
        content = f.read()

    conn.sendall(b"HTTP/1.1 200 OK\r\n")
    conn.sendall(f"Content-length: {len(content)}\r\n".encode())
    conn.sendall(b"\r\n")
    conn.sendall(content)
    conn.close()


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.bind(("localhost", 8081))
    s.listen(5)
    while 1:
        conn, addr = s.accept()
        print(("# Connected with " + addr[0]))
        try:
            handle_request(conn)
        finally:
            conn.close()
finally:
    s.close()

暂无
暂无

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

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