摘要:對進行包裝,采用注冊回調方式實現非阻塞。通過接口注冊各個事件回調中事件發生后,調用方法,對事件進行分發。
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> # #