我的代理服务器在python中

时间:2018-04-02 16:00:23

标签: python http networking server

我是计算机网络的新手,我想创建自己的代理服务器。
但是当我将从客户端收到的请求发送到服务器时,我无法从服务器获得响应。我的代码在这里得到例外:

LINQPad.User

以下是从客户收到的请求

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()

1 个答案:

答案 0 :(得分:0)

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