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

Python缓存代理服务器无法正常运行问题求助

简单代理服务器代码运行无响应问题排查

我编写了一段Python代码实现具备网页缓存功能的简单代理服务器,该服务器仅支持GET请求,可处理HTML页面、图片等各类对象。但运行该代码后无任何反应,已开启Windows的代理设置,通过CMD运行程序后没有继续执行,求技术帮助。

原代码

From socket import *
import sys
if len(sys.argv) <= 1: print ('Usage :"python ProxyServer.py server_ip"\n[server_ip : It is the IP Address OfProxy Server')
sys.exit(2)

# Create a server socket, bind it to a port and start listening 
tcpSerSock = socket(AF_INET, SOCK_STREAM)
# Fill in start.
tcpSerSock.bind((sys.argv[1], 8888))
tcpSerSock.listen(5)
# Fill in end.

while 1:
  # Strat receiving data from the client
  print( 'Ready to serve...')
  tcpCliSock, addr = tcpSerSock.accept()
  print ('Received a connection from:', addr )
  message = tcpCliSock.recv(1024).decode() # Fill in start.
  print(message)               # Fill in end. 

  # Extract the filename from the given message print message.split()[1]
  filename = message.split()[1].partition("/")[2]
  print(filename)
  fileExist = "false"
  filetouse = "/" + filename

  print (filetouse)
  try:
    # Check wether the file exist in the cache
    f = open(filetouse[1:], "r")
    outputdata = f.readlines()
    fileExist = "true"

    # ProxyServer finds a cache hit and generates a response message     
    tcpCliSock.send("HTTP/1.0 200 OK\r\n") 
    tcpCliSock.send("Content-Type:text/html\r\n")
    # Fill in start.
    for line in outputdata:
        tcpCliSock.send(line.encode())
    #f.close()
    # Fill in end.
    print ('Read from cache')
  # Error handling for file not found in cache
  except IOError:
      if fileExist == "false":
        # Create a socket on the proxyserver
        c = socket(AF_INET, SOCK_STREAM)# Fill in start. # Fill in end. 
        hostn = filename.replace("www.","",1)
        print (hostn)
        try:
            # Connect to the socket to port 80
            # Fill in start.
            c.connect((hostn, 80))
            # Fill in end.

            # Create a temporary file on this socket and ask port 80 for the file requested by the client
            fileobj = c.makefile('r', 0)
            fileobj.write("GET "+"http://" + filename + " HTTP/1.0\n\n")

            # Read the response into buffer
            # Fill in start.
            buffer = fileobj.read()
            # Fill in end.

            # Create a new file in the cache for the requested file. 
            # Also send the response in the buffer to client socket and the corresponding file in the cache
            tmpFile = open("./" + filename,"wb")
            # Fill in start.
            tmpFile.write(buffer)
            tmpFile.close()
            tcpCliSock.send(buffer.encode())
            # Fill in end.
        except:
                print ("Illegal request")
else:
    # HTTP response message for file not found 
    # Fill in start.
    tcpCliSock.send("HTTP/1.0 404 Not Found\r\n".encode())
    tcpCliSock.send("Content-Type:text/html\r\n".encode())
    tcpCliSock.send("\r\n".encode())
    tcpCliSock.send("<html><body><h1>404 Not Found</h1></body></html>\r\n".encode())
    # Fill in end.
    # Close the client and the server sockets
    tcpCliSock.close()
# Fill in start.
tcpSerSock.close()
# Fill in end’

问题分析与修复方案

1. 语法错误(直接导致程序无法启动)

  • 导入语句错误:第一行From socket import *需改为小写from socket import *,Python对大小写敏感,大写开头会导致导入失败。
  • 缩进错误:sys.exit(2)需与上方if语句同级,否则无论是否传入参数都会直接退出程序;except IOError后的else需缩进,属于try-except结构的一部分,当前位置会触发语法错误。
  • 符号错误:末尾注释# Fill in end’的单引号为中文符号,需改为英文单引号'。

2. 启动与代理配置问题

  • 启动参数缺失:运行时需指定代理服务器IP,例如python ProxyServer.py 127.0.0.1,若未传参数,原代码提示后直接退出,需确保传参正确。
  • 代理设置匹配:Windows代理设置需指向绑定的IP(如127.0.0.1)和端口8888,且设置为HTTP代理(代码仅处理HTTP请求)。

3. 逻辑与协议问题

  • HTTP协议格式错误:向目标服务器发送请求时,换行符需用\r\n而非\n,原代码中请求格式不符合HTTP规范,需修正为f"GET {path} HTTP/1.0\r\nHost: {hostn}\r\n\r\n",避免重复携带域名。
  • 缓存路径处理:直接用./+filename创建文件可能因目录不存在报错,需先检查并创建对应目录(可使用os.makedirs)。
  • 空请求处理:若客户端连接后未发送数据,message.split()会抛出异常,需先判断message是否为空再处理。
  • 资源泄漏:注释掉的f.close()需恢复,避免文件句柄泄漏;客户端和服务器套接字需在异常场景下正确关闭。

修正后的代码示例

from socket import *
import sys
import os

if len(sys.argv) <= 1:
    print('Usage: "python ProxyServer.py server_ip"\n[server_ip : It is the IP Address Of Proxy Server]')
    sys.exit(2)

# Create a server socket, bind it to a port and start listening 
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind((sys.argv[1], 8888))
tcpSerSock.listen(5)

while True:
    print('Ready to serve...')
    tcpCliSock, addr = tcpSerSock.accept()
    print('Received a connection from:', addr )
    try:
        message = tcpCliSock.recv(1024).decode()
        if not message:
            tcpCliSock.close()
            continue
        print(message)

        # Extract request path and host
        request_line = message.split('\n')[0]
        url = request_line.split()[1]
        host_start = url.find('://') + 3
        host_end = url.find('/', host_start)
        if host_end == -1:
            host_end = len(url)
        hostn = url[host_start:host_end]
        path = url[host_end:] if host_end < len(url) else '/'
        filename = f"{hostn}{path}".replace('/', '_').replace(':', '_')

        fileExist = False
        filetouse = f"./{filename}"

        try:
            # Check whether the file exists in the cache
            with open(filetouse, "rb") as f:
                outputdata = f.read()
                fileExist = True

                # Send response from cache
                tcpCliSock.send(b"HTTP/1.0 200 OK\r\n")
                tcpCliSock.send(b"Content-Type: text/html\r\n")
                tcpCliSock.send(b"Content-Length: %d\r\n\r\n" % len(outputdata))
                tcpCliSock.send(outputdata)
                print('Read from cache')
        except IOError:
            if not fileExist:
                # Create socket to connect to target server
                c = socket(AF_INET, SOCK_STREAM)
                try:
                    c.connect((hostn, 80))
                    # Send correct HTTP request
                    request = f"GET {path} HTTP/1.0\r\nHost: {hostn}\r\n\r\n"
                    c.send(request.encode())

                    # Read response
                    buffer = b""
                    while True:
                        data = c.recv(4096)
                        if not data:
                            break
                        buffer += data

                    # Save to cache
                    os.makedirs(os.path.dirname(filetouse), exist_ok=True)
                    with open(filetouse, "wb") as tmpFile:
                        tmpFile.write(buffer)

                    # Send response to client
                    tcpCliSock.send(buffer)
                except Exception as e:
                    print(f"Error connecting to server: {e}")
                    # Send 404 response
                    tcpCliSock.send(b"HTTP/1.0 404 Not Found\r\n")
                    tcpCliSock.send(b"Content-Type:text/html\r\n\r\n")
                    tcpCliSock.send(b"<html><body><h1>404 Not Found</h1></body></html>\r\n")
                finally:
                    c.close()
            else:
                # Send 404 response
                tcpCliSock.send(b"HTTP/1.0 404 Not Found\r\n")
                tcpCliSock.send(b"Content-Type:text/html\r\n\r\n")
                tcpCliSock.send(b"<html><body><h1>404 Not Found</h1></body></html>\r\n")
    except Exception as e:
        print(f"Error handling client: {e}")
    finally:
        tcpCliSock.close()

tcpSerSock.close()

内容的提问来源于stack exchange,提问作者The Choumans

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 12:44:55