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

python索引器错误:当我尝试从字符串中获取单个字符时,字符串索引超出范围,python,Python,我正在尝试用python制作一个简单的套接字服务器,它能够为多个文件提供服务,但我遇到了以下错误: Traceback (most recent call last): File "webserver.py", line 43, in <module> if b[x] == "G": IndexError: string index out of range 您没有在连接之间将x重置为零 第一个连接可能工作正常,但对于后续连接,x不在范围内 也就是说,您可能只想使用b.

我正在尝试用python制作一个简单的套接字服务器,它能够为多个文件提供服务,但我遇到了以下错误:

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

您没有在连接之间将
x
重置为零

第一个连接可能工作正常,但对于后续连接,
x
不在范围内

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

不过,为了便于练习,下面是对代码的一种修改,它适用于多个后续连接:

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

如果出现此错误,则x大于字符串的最后一个索引
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()