摘要:对进行包装,采用注册回调方式实现非阻塞。通过接口注册各个事件回调中事件发生后,调用方法,对事件进行分发。
iostream.py
A utility class to write to and read from a non-blocking socket.
IOStream 对 socket 进行包装,采用注册回调方式实现非阻塞。
通过接口注册各个事件回调
_read_callback
_write_callback
_close_callback
_connect_callback
ioloop 中 socket 事件发生后,调用 IOStream._handle_events 方法,对事件进行分发。
对应的事件处理过程中,如果满足注册的回调条件,则调用回调函数
回调函数在 IOStream._handle_events 中被调用
iostream.py
contents
example
head
IOStream.__init__
IOStream.connect
IOStream.read_until
IOStream.read_bytes
IOStream.write
IOStream.close
IOStream._handle_events
IOStream._run_callback
IOStream._run_callback
IOStream._read_from_socket
IOStream._read_to_buffer
IOStream._read_from_buffer
IOStream._handle_connect
IOStream._handle_write
IOStream._consume
IOStream._add_io_state
IOStream._read_buffer_size
copyright
example一个简单的 IOStream 客户端示例
由此可见, IOStream 是一个异步回调链
创建 socket
创建 IOStream 对象
连接到主机,传入连接成功后回调函数 send_request
socket 输出数据请求页面,读取 head,传入读取 head 成功后回调函数 on_headers
继续读取 body,传入读取 body 成功后回调函数 on_body
关闭 stream,关闭 ioloop
from tornado import ioloop from tornado import iostream import socket def send_request(): stream.write("GET / HTTP/1.0 Host: baidu.com ") stream.read_until(" ", on_headers) def on_headers(data): headers = {} for line in data.split(" "): parts = line.split(":") if len(parts) == 2: headers[parts[0].strip()] = parts[1].strip() stream.read_bytes(int(headers["Content-Length"]), on_body) def on_body(data): print data stream.close() ioloop.IOLoop.instance().stop() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) stream = iostream.IOStream(s) stream.connect(("baidu.com", 80), send_request) ioloop.IOLoop.instance().start() # html> # #