此時服務器啓動poo對象在等待客戶端有鏈接請求服務器
當client發送請求時先創建鏈接app
event_pairs = self._impl.poll(poll_timeout)socket
此時event_pairs 中保存了事件函數
fd, events = self._events.popitem()oop
try:this
fd_obj, handler_func = self._handlers[fd]spa
handler_func(fd_obj, events)orm
此時的fd爲 監聽的fd,調用監聽對象的回調函數,也就是accept_handlerserver
看 accept_handler代碼:對象
def accept_handler(fd, events):
for i in xrange(_DEFAULT_BACKLOG):
try:
connection, address = sock.accept()
except socket.error as e:
# _ERRNO_WOULDBLOCK indicate we have accepted every
# connection that is available.
if errno_from_exception(e) in _ERRNO_WOULDBLOCK:
return
# ECONNABORTED indicates that there was a connection
# but it was closed while still in the accept queue.
# (observed on FreeBSD).
if errno_from_exception(e) == errno.ECONNABORTED:
continue
raise
callback(connection, address)
先調用accept獲取客戶端鏈接對象而後調用callback,此時callback是:
_handle_connection,也就是 TCPServer::_handle_connection,不考慮https鏈接
建立一個IOStream對象,而後調用 handle_stream,此時的handle_stream其實是
HTTPServer::handle_stream,而後建立一個對應的鏈接對象HTTP1ServerConnection
_connections 中保存該對象,調用對象的start_serving方法
先看 start_serving 方法:
def start_serving(self, delegate):
"""Starts serving requests on this connection.
:arg delegate: a `.HTTPServerConnectionDelegate`
"""
assert isinstance(delegate, httputil.HTTPServerConnectionDelegate)
self._serving_future = self._server_request_loop(delegate)
# Register the future on the IOLoop so its errors get logged.
self.stream.io_loop.add_future(self._serving_future,
lambda f: f.result())
這個函數的參數實際上就是 httpserver對象
調用了_server_request_loop,
在 _server_request_loop 中用@gen.coroutine進行了裝飾
@gen.coroutine
def _server_request_loop(self, delegate):
此時的
request_delegate = delegate.start_request(self, conn)
實際調用的是
HTTPServer::start_request
調用 _ServerRequestAdapter
在 _ServerRequestAdapter::__init__中, 調用
server.request_callback.start_request(connection)
Application::start_request 返回_RequestDispatcher,結果就是
request_delegate 指向的對象爲 _RequestDispatcher
而後在 gen.coroutine 中調用 _make_coroutine_wrapper,在_make_coroutine_wrapper中
調用yielded = next(result)時,調用的就是
_server_request_loop中的conn.read_response(request_delegate)
此時傳入的參數實際上就是RequestDispatcher
而後調用_read_message
而後調用delegate.finish() == _RequestDispatcher::finish()
調用 self.execute()
流程代碼:
self.handler = self.handler_class(self.application, self.request,
**self.handler_kwargs)
self.handler._execute(transforms, *self.path_args, **self.path_kwargs)
在 _execute 中調用
result = method(*self.path_args, **self.path_kwargs)
在上面的demo的get方法中,咱們調用self.write("0"),在write的方法中
實際只是把內容放在writebuffer中
self._write_buffer.append(chunk)
而後調用self.finish()
其中調用了self.flush(include_footers=True)
調用
self.request.connection.write_headers(
start_line, self._headers, chunk, callback=callback)
或者
Self.request.connection.write
而後調用self.request.finish()
而後調用HTTP1Connection::finish()
而後調用 HTTP1Connection::_finish_request()
而後判斷是否須要斷開鏈接
if not self.is_client and self._disconnect_on_finish:
self.close()
return