Skip to main content
 首页 » 编程设计

python之使用套接字 API 编写基本的 HTTP 服务器

2025年02月15日11zengkefu

我的 server.py 文件中有以下代码。它正在等待从客户端接收数据。此外,我不能使用任何 http 库。只有套接字库:

def handle_client(conn, addr): 
    print ('New client from', addr) 
    x = [] 
    try: 
        while True: 
            data = conn.recv(1024) 
            decoded_data = data.decode('utf-8') 
            # if "GET / " in data.decode('utf-8'): 
            #   handle_client_get(conn) 
            # else: 
            if data: 
                print(data) 
                x.append(decoded_data) 
            else: 
                print(x) 
                break 
    finally: 
        print("in close now") 
        conn.close() 

我遇到的问题是,我只能在手动 CTRL + C 关闭客户端后到达 print(x) 语句。否则不打印。

为什么会这样。

回答

您需要向客户端发送确认,以便已正确接收发送的数据。

这将终止连接而不是等待超时。

这是因为客户端发送:Expect: 100-continue 并且您需要将确认发送回客户端

请您参考如下方法:

你需要实现协议(protocol),它会告诉你有多少数据要读取。在 HTTP 的情况下,请求以 CRLF 分隔的 header 开头,我们可以读取它以获取我们想要的信息。

w3.org 对 http request protocol 有很好的描述.它比我想在这里实现的更复杂,但我已经包含了一个示例,该示例通过一次读取套接字一个字符并查找空的 \n 终止行来拉入请求 header 。通过一次读取一个字符,我不必实现自己的行缓冲区。

第一行是请求方法,其余行是请求中包含的其他参数。例如,对于 POST,还有更多数据需要从套接字中读取。

import re 
 
def handle_client(conn, addr): 
    print ('New client from', addr) 
    header = [] 
    line = [] 
    try: 
        # read ascii http client header.  
        while True: 
            c = conn.recv(1) 
            # check for early termination 
            if not c: 
                return None 
            # check for end of request line 
            elif c == b"\n": 
                # make line a string to add to header 
                line = ''.join(line).decode('ascii').strip() 
                # are we at the empty line signalling end-of-header? 
                if not line: 
                    break 
                header.append(line) 
                line = [] 
            # filter out \r 
            elif c == b"\r": 
                continue 
 
        # request is first line of header 
        request_line = header.pop(0) 
        method, uri, http_version = re.split(r" +" request_line) 
 
        if method.upper() == "GET": 
            # this function needs more parameters... the uri to get and the protocol 
            # version to use. 
            handle_client_get(...) 
    finally: 
        print("in close now") 
        conn.close()