Tornado io_loop

import errno
import functools
import socket

import tornado.ioloop
from tornado.iostream import IOStream


async def handler_connection(connection, address):
stream = IOStream(connection)
message = await stream.read_until_close()
print("message from client : ", message.decode().strip())


def connection_ready(sock, fd, events):
while True:
try:
connection, address = sock.accept()
except socket.error as e:
if e.args[0] not in [errno.EWOULDBLOCK, errno.EAGAIN]:
raise
return
connection.setblocking(0)
io_loop = tornado.ioloop.IOLoop.current()
io_loop.spawn_callback(handler_connection, connection, address)

if __name__ == '__main__':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setblocking(0)
sock.bind(('',8888))
sock.listen(12)
io_loop = tornado.ioloop.IOLoop.current()
callback = functools.partial(connection_ready, sock)
io_loop.add_handler(sock.fileno(), callback, io_loop.READ)
io_loop.start()


#创建socket 连接后,获取tornado 的事件循环,然后把 socket 句柄和回调函数注册到事件循环中.可以循环每个socket连接





posted @ 2020-06-16 13:33  AndRew-A  阅读(291)  评论(0编辑  收藏  举报