import asyncore
class HTTPClient(asyncore.dispatcher):
def __init__(self, host, path):
asyncore.dispatcher.__init__(self)
self.create_socket()
self.connect( (host, 80) )
self.buffer = bytes('GET %s HTTP/1.0\r\nHost: %s\r\n\r\n' %
(path, host), 'ascii')
def handle_connect(self):
pass
def handle_close(self):
self.close()
def handle_read(self):
print(self.recv(8192))
def writable(self):
return (len(self.buffer) > 0)
def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]
client = HTTPClient('www.bocaonews.com.br', '/')
asyncore.loop()
并引发了一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "***.py", line 15, in __init__
self.connect( (host, 80) )
File "***\lib\asyncore.py", line 339, in connect
err = self.socket.connect_ex(address)
socket.gaierror: [Errno 11004] getaddrinfo failed
HTTP客户端是官方文档的示例。由于无法访问主机 www.bocaonews.com.br,因此引发了错误。
所以我的问题是如何修改代码让客户端在主机坏的时候自动关闭连接?我可以在生成调度程序之前检查主机。但它的效率较低。