摘要:對(duì)進(jìn)行包裝,采用注冊(cè)回調(diào)方式實(shí)現(xiàn)非阻塞。通過接口注冊(cè)各個(gè)事件回調(diào)中事件發(fā)生后,調(diào)用方法,對(duì)事件進(jìn)行分發(fā)。
iostream.py
A utility class to write to and read from a non-blocking socket.
IOStream 對(duì) socket 進(jìn)行包裝,采用注冊(cè)回調(diào)方式實(shí)現(xiàn)非阻塞。
通過接口注冊(cè)各個(gè)事件回調(diào)
_read_callback
_write_callback
_close_callback
_connect_callback
ioloop 中 socket 事件發(fā)生后,調(diào)用 IOStream._handle_events 方法,對(duì)事件進(jìn)行分發(fā)。
對(duì)應(yīng)的事件處理過程中,如果滿足注冊(cè)的回調(diào)條件,則調(diào)用回調(diào)函數(shù)
回調(diào)函數(shù)在 IOStream._handle_events 中被調(diào)用
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一個(gè)簡(jiǎn)單的 IOStream 客戶端示例
由此可見, IOStream 是一個(gè)異步回調(diào)鏈
創(chuàng)建 socket
創(chuàng)建 IOStream 對(duì)象
連接到主機(jī),傳入連接成功后回調(diào)函數(shù) send_request
socket 輸出數(shù)據(jù)請(qǐng)求頁面,讀取 head,傳入讀取 head 成功后回調(diào)函數(shù) on_headers
繼續(xù)讀取 body,傳入讀取 body 成功后回調(diào)函數(shù) on_body
關(guān)閉 stream,關(guān)閉 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> # #