You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Socket Web服务器中获取客户端请求的链接?

解决方法

要获取浏览器请求的URL路径,你需要解析HTTP请求报文——浏览器通过Socket发送给服务器的是符合HTTP协议格式的文本内容,第一行就包含了请求路径。

具体步骤:

  • 用客户端套接字c接收请求数据,解码为字符串
  • 拆分请求内容,提取第一行的请求路径
  • 根据路径读取对应文件,组装HTTP响应返回给浏览器

完整代码示例

import socket
from socket import AF_INET, SOCK_STREAM

s = socket(AF_INET, SOCK_STREAM)
s.bind(('localhost', 8080))
s.listen(1)

print("服务器运行在 http://localhost:8080")

while True:
    try:
        c, addr = s.accept()
        # 接收请求数据,设置1024字节接收大小,足够处理基础请求
        request_data = c.recv(1024).decode('utf-8')
        if not request_data:
            c.close()
            continue
        
        # 解析请求第一行,提取路径
        request_lines = request_data.split('\n')
        first_line = request_lines[0].strip()
        # 拆分第一行:比如 "GET /mysite.html HTTP/1.1" 拆分为三个部分
        method, path, protocol = first_line.split()
        
        # 处理根路径,默认返回index.html
        if path == '/':
            path = '/index.html'
        
        # 尝试读取文件
        try:
            with open('.' + path, 'rb') as f:
                file_content = f.read()
                # 组装成功的HTTP响应头
                response_header = f"{protocol} 200 OK\r\n"
                response_header += "Content-Type: text/html; charset=utf-8\r\n"
                response_header += f"Content-Length: {len(file_content)}\r\n"
                response_header += "\r\n"  # 响应头和内容之间的分隔空行
                # 发送响应:先头发送字符串转字节,再发文件内容
                c.send(response_header.encode('utf-8'))
                c.send(file_content)
        except FileNotFoundError:
            # 文件不存在返回404响应
            response = f"{protocol} 404 Not Found\r\n"
            response += "Content-Type: text/html; charset=utf-8\r\n"
            response += "\r\n"
            response += "<h1>404 页面未找到</h1>"
            c.send(response.encode('utf-8'))
        finally:
            c.close()
    except KeyboardInterrupt:
        print("服务器停止")
        break
s.close()

关键说明:

  • HTTP请求第一行格式固定为[请求方法] [请求路径] [HTTP版本],拆分后即可拿到目标path
  • 读取文件用rb模式,避免编码问题,直接返回字节内容
  • 必须严格按照HTTP协议组装响应头:包含状态码、内容类型、内容长度,且响应头与内容之间必须有一个空行(\r\n\r\n)
  • 需处理异常场景:比如文件不存在返回404、请求为空的情况

内容的提问来源于stack exchange,提问作者Kevin Li

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 06:30:06