Python 简单套接字 - 从客户端请求获取 URL

Eth*_*ill 2 python sockets tcp python-3.x

对于一项学校作业,我需要填写一个充当简单代理服务器的示例 Python 3 应用程序的空白。我只需要使用套接字库。

我的问题在于,我没有被教导如何从客户端提取请求的 URL,也无法在网上找到帮助我的信息。这是到目前为止的代码(我将它们包含在内是为了给出我需要编写的 Python 风格的示例):

from socket import socket, gethostname, AF_INET, SOCK_STREAM
import sys

if len(sys.argv) <= 1:
    print ("Usage : 'python ProxyServer.py server_ip'\nserver_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(('localhost', 8888))
tcpSerSock.listen(5)

while 1: 

    # Start receiving data from the client 
    print ('Ready to serve...' )

    tcpCliSock, addr = tcpSerSock.accept()
    print ('Received a connection from:', addr)

    message = addr

    print (message.value)

    # Extract the filename from the given message     
    filename = message.split()[1].partition("/")[2] 
    print (filename)
Run Code Online (Sandbox Code Playgroud)

当我对页面进行排队时,我导航到“localhost:8080/www.google.com/”。

我的问题是,在 Python 中,我如何能够从排队的 URL 中以字符串形式读取“www.google.com”?

Eth*_*ill 6

这就是我找到的答案。

tcpCliSock.recv(4096)
Run Code Online (Sandbox Code Playgroud)

^ 上面返回一个包含完整请求的字节对象。当转换为字符串并根据空格分割时,请求的“www.google.com”段位于位置 [1]。

在我的脑海中,检索 URL 将如下所示:

test = message.split()[1]
Run Code Online (Sandbox Code Playgroud)