繁体   English   中英

我在python中的代理服务器

[英]my proxy server in python

我是计算机网络的新手,我正努力制作自己的代理服务器。
但是,当我将从客户端收到的请求发送到服务器时,我无法从服务器获得响应。 我的代码在这里出现异常:

try:
    # connect
    serverSock.connect((hostName, 80))

    # get the client's request
    fp = open("requestCache.txt", "r")
    message = fp.read()
    fp.close()

    # send to the target server
    serverSock.send(message)
    response = serverSock.recv(4096)

    # send to the client
    tcpCliSock.send(response)

except:
    print('connect failed!')
    serverSock.close()

以下是从客户端收到的请求

GET /www.baidu.com HTTP/1.1 Host: localhost:3009 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh;q=0.9

您通常希望避免在try...except块中包含大量代码,除非您确切了解引发异常时会发生什么。 我通常将try...except块保持尽可能少,并捕获尽可能多的特定错误:

try:
    serverSock.connect((hostName, 80))
except OSError as e:
    # handle e

您实际上正在捕获并丢弃一个非常有用的错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-13-78a255a190f8> in <module>()
     10
     11 # send to the target server
---> 12 serverSock.send(message)
     13 response = serverSock.recv(4096)
     14

TypeError: a bytes-like object is required, not 'str'

您的message是一个字符串,但是套接字处理字节。 要修复它,请读取文件内容而不是字节( 'rb'模式,而不仅仅是'r' ):

# connect
serverSock.connect((hostName, 80))

# get the client's request
with open("requestCache.txt", "rb") as handle:
    message = handle.read()

# send to the target server
serverSock.send(message)
response = serverSock.recv(4096)

# send to the client
tcpCliSock.send(response)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM