【问题标题】:my proxy server in python我在 python 中的代理服务器
【发布时间】:2018-09-11 20:42:42
【问题描述】:

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

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

【问题讨论】:

  • 您是否尝试过查看抛出的异常(例如,除了 Exception as ex: print(ex))?

标签: python http networking server


【解决方案1】:

您通常希望避免在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)

【讨论】:

  • 谢谢!保持 try..except 块中的块代码尽可能小,这对我有很大帮助!
猜你喜欢
  • 1970-01-01
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-30
相关资源
最近更新 更多