代码
使用 Tornado IOStream.read_until_close 读取 http 响应。
from tornado import ioloop
from tornado import iostream
import socket
class Client(object):
def __init__(self, domen, uri):
self.uri = uri
self.domen = domen
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
self.stream = iostream.IOStream(s)
def open(self):
self.stream.connect((self.domen, 80), self.send_request)
def on_chunk_read(self, chunk):
print "chunk\n", chunk
def on_close(self, res):
print "res\n", res
self.stream.close()
ioloop.IOLoop.instance().stop()
def send_request(self):
self.stream.write(
"GET %s HTTP/1.0\r\nHost: %s\r\n\r\n" % (self.uri, self.domen))
self.stream.read_until_close(self.on_close, self.on_chunk_read)
client = Client("www.google.com", "/")
client.open()
ioloop.IOLoop.instance().start()
输出
res
HTTP/1.0 302 Found
Location: http://www.google.ru/
...
<HTML>
...
</HTML>
文档tornado.iostream
read_until_close(callback, streaming_callback=None)
Reads all data from the socket until it is closed.
If a streaming_callback is given, it will be called with chunks of data as they
become available, and the argument to the final callback will be empty.
Subject to max_buffer_size limit from IOStream constructor if a
streaming_callback is not used.
结论
未调用代码'print "chunk\n", chunk'。调用回调,但未调用 streaming_callback。
是bug吗?