python里使用协程来创建echo服务器

来源:互联网 发布:唯品会秒杀软件 编辑:程序博客网 时间:2024/05/18 03:46
asyncio库的主作用就是用来构造基于I/O方面的程序。在这里通过一个echo服务器来学会怎么使用协程来创建服务器的方式。
每次I/O操作完成之后,就会释放控制权,交回到事件循环里。

代码如下:

import asyncioimport loggingimport sysSERVER_ADDRESS = ('localhost', 10000)class EchoServer(asyncio.Protocol):    def connection_made(self, transport):        self.transport = transport        self.address = transport.get_extra_info('peername')        self.log = logging.getLogger(            'EchoServer_{}_{}'.format(*self.address)        )        self.log.debug('connection accepted')    def data_received(self, data):        self.log.debug('received {!r}'.format(data))        self.transport.write(data)        self.log.debug('sent {!r}'.format(data))    def eof_received(self):        self.log.debug('received EOF')        if self.transport.can_write_eof():            self.transport.write_eof()    def connection_lost(self, error):        if error:            self.log.error('ERROR: {}'.format(error))        else:            self.log.debug('closing')        super().connection_lost(error)logging.basicConfig(    level=logging.DEBUG,    format='%(name)s: %(message)s',    stream=sys.stderr,)log = logging.getLogger('main')event_loop = asyncio.get_event_loop()# Create the server and let the loop finish the coroutine before# starting the real event loop.factory = event_loop.create_server(EchoServer, *SERVER_ADDRESS)server = event_loop.run_until_complete(factory)log.debug('starting up on {} port {}'.format(*SERVER_ADDRESS))# Enter the event loop permanently to handle all connections.try:    event_loop.run_forever()finally:    log.debug('closing server')    server.close()    event_loop.run_until_complete(server.wait_closed())    log.debug('closing event loop')    event_loop.close()

在代码开始地方导入asyncio和logging库,接着创建一个事件循环。
继承类asyncio.Protocol,创建子类EchoServer来处理与客户端的通讯。
当服务器接收到连接时,就会调用函数connection_made(self, transport),参数transport是连接的socket封装。
当连接收到数据时,就会调用函数data_received(self, data),参数data是接收到的数据。
当有一些情况下的连接收到EOF字符,就调用函数eof_received(self)。
当连接关闭时,就会调用connection_lost(self, error),参数error是告诉出错原因。


logging.basicConfig是定义调试输出LOG类。
event_loop.create_server(EchoServer, *SERVER_ADDRESS)是创建服务器协程运行,调用
event_loop.run_until_complete(factory)来运行。  
另外想服务器程序不要退出就运行event_loop.run_forever()。

Python游戏开发入门

http://edu.csdn.net/course/detail/5690

你也能动手修改C编译器

http://edu.csdn.net/course/detail/5582

纸牌游戏开发

http://edu.csdn.net/course/detail/5538 

五子棋游戏开发

http://edu.csdn.net/course/detail/5487
RPG游戏从入门到精通
http://edu.csdn.net/course/detail/5246
WiX安装工具的使用
http://edu.csdn.net/course/detail/5207
俄罗斯方块游戏开发
http://edu.csdn.net/course/detail/5110
boost库入门基础
http://edu.csdn.net/course/detail/5029
Arduino入门基础
http://edu.csdn.net/course/detail/4931
Unity5.x游戏基础入门
http://edu.csdn.net/course/detail/4810
TensorFlow API攻略
http://edu.csdn.net/course/detail/4495
TensorFlow入门基本教程
http://edu.csdn.net/course/detail/4369
C++标准模板库从入门到精通 
http://edu.csdn.net/course/detail/3324
跟老菜鸟学C++
http://edu.csdn.net/course/detail/2901
跟老菜鸟学python
http://edu.csdn.net/course/detail/2592
在VC2015里学会使用tinyxml库
http://edu.csdn.net/course/detail/2590
在Windows下SVN的版本管理与实战 
http://edu.csdn.net/course/detail/2579
Visual Studio 2015开发C++程序的基本使用 
http://edu.csdn.net/course/detail/2570
在VC2015里使用protobuf协议
http://edu.csdn.net/course/detail/2582
在VC2015里学会使用MySQL数据库
http://edu.csdn.net/course/detail/2672