2

代码

使用 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吗?

4

1 回答 1

2

我认为这不是一个错误,取决于流的长度,作为一个或块发送给你。

def on_chunk_read(self, chunk):
    print "chunk\n", len(chunk)

def on_close(self, res):
    print "res\n", len(res)
    self.stream.close()
    ioloop.IOLoop.instance().stop()

1.one,重定向,只有标题的短内容。

client = Client("www.google.com", "/")

输出

res
1279

2.块,

client = Client("www.google.ru", "/")

chunk
4837
chunk
1418
chunk
1418
chunk
1418
...
chunk
1418
res
1093
于 2012-10-12T06:06:34.903 回答