我写了一个简短的类来帮助我测试向我正在处理的服务器发送纯文本 http 请求,但是我用它发出的所有请求都没有通过,甚至对我的服务器以外的域的请求也是如此。所有请求都超时。该类只是 python 的 socket 模块的包装器。有趣的是,这门课几个月前还可以正常工作。从那以后我就没有碰过代码。
资源:
class TCPClient:
def __init__(self):
self.connection = None
def sendMessage(self, message):
if self.connection:
bytes_sent = self.connection.send(message)
print "bytes_sent: %d"%bytes_sent
else:
print 'No open connection.'
def getResponse(self, buffer_size=1024):
response = ""
start_time = time.time()
curr_time = time.time()
frombuff = 1
while frombuff and ((curr_time - start_time) < 5):
curr_time = time.time()
frombuff = self.connection.recv(buffer_size)
try:
frombuff = self.connection.recv(buffer_size)
response += frombuff
except Exception as e:
logging.error("Exception thrown while receiving bytes")
logging.error(e)
frombuff = None
return
return response
def openConnection(self, IP, PORT, timeout=2):
if self.connection:
self.connection.close()
self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connection.connect((IP, PORT))
self.connection.settimeout(timeout)
def closeConnection(self):
if self.connection:
self.connection.close()
self.connection = None
else:
print 'No open connection.'
这是我用来测试它的脚本,做了一些修改。我一直试图发出的实际请求是对我的实时服务器的,请求在浏览器中和 python 的请求库中工作。出于隐私原因,我无法在此处列出。下面的请求也会超时。
测试脚本:
from tcp import TCPClient
msg = "GET /whatever HTTP/1.1\r\n\
Host: google.com\r\n\
Connection: Keep-Alive\r\n\
\r\n"
#expecting a proper 404
client = TCPClient()
client.openConnection(HOST, PORT)
client.sendMessage(msg)
res = client.getResponse()
print res
任何帮助表示赞赏。谢谢!
编辑
超时在 getResponse() 的 try/except 块中被捕获。输出如下所示:
ERROR:root:Exception thrown while receiving bytes
ERROR:root:timed out