提供了幾個'BaseProtocol', 'Protocol', 'DatagramProtocol''SubprocessProtocol' 實例git
基本的方法:github
connection_made() data_received() # 這個是相似於一個循環,循環調用者個方法來讀取內容 eof_received() connection_lost()
啓動順序依次是socket
State machine of calls: start -> CM [-> DR*] [-> ER?] -> CL -> end * CM: connection_made() * DR: data_received() * ER: eof_received() * CL: connection_lost()
create_serverasync
def create_server(self, protocol_factory, host=None, port=None, *, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None): # 用來創建一個TCP 類型的Server,提供了默認的一些參數 關於詳細的內容能夠查看asyncio.events 模塊 protocol_factory 咱們使用asyncio.Protocol 來作工廠函數
create_connection()函數
def create_connection(self, protocol_factory, host=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None): raise NotImplementedError
asyncio事件循環oop
loop = asyncio.get_event_loop()
class EchoServerClientProtocol(asyncio.Protocol): def connection_made(self, transport): peername = transport.get_extra_info('peername') print('Connection from {}'.format(peername)) self.transport = transport self.word_title = '咱們一塊兒來背誦 <<荷葉杯·記得那年花下>>' self.word_list = ['記得那年花下', '深夜', '初識謝娘時', '水堂西面畫簾垂', '攜手暗相期', '惆悵曉鶯殘月', '相別', '今後隔音塵', '現在俱是異鄉人', '相見更無因'] self.index = 0 def data_received(self, data): message = data.decode() print('Data received: {!r}'.format(message)) try: message = self.find_next(data=data.decode()) print('Send: {!r}'.format(message)) self.transport.write(message.encode()) except (IndexError,ValueError): message = input('input the message:') print('Send: {!r}'.format(message)) self.transport.write(message.encode()) def find_next(self, data): index = self.word_list.index(data) return self.word_list[index + 1] loop = asyncio.get_event_loop() # Each client connection will create a new protocol instance coro = loop.create_server(EchoServerClientProtocol, '127.0.0.1', 8888) server = loop.run_until_complete(coro) # Serve requests until Ctrl+C is pressed print('Serving on {}'.format(server.sockets[0].getsockname())) try: loop.run_forever() except KeyboardInterrupt: pass # Close the server server.close() loop.run_until_complete(server.wait_closed()) loop.close()
class EchoClientProtocol(asyncio.Protocol): def __init__(self, loop): self.loop = loop self.transport = None self.word_title = '咱們一塊兒來背誦 <<荷葉杯·記得那年花下>>' self.word_list = ['記得那年花下', '深夜', '初識謝娘時', '水堂西面畫簾垂', '攜手暗相期', '惆悵曉鶯殘月', '相別', '今後隔音塵', '現在俱是異鄉人', '相見更無因'] self.index = 0 print(self.word_title) def connection_made(self, transport): self.transport = transport message = self.word_list[self.index] print('message: ',message) self.transport.write(message.encode()) def data_received(self, data): print('Data received: {!r}'.format(data.decode())) try: message = self.find_next(data=data.decode()) self.transport.write(message.encode()) print('Data sent: {!r}'.format(message)) except (IndexError,ValueError): message = input('input message:') self.transport.write(message.encode()) print('Data sent: {!r}'.format(message)) def connection_lost(self, exc): print('The server closed the connection') print('Stop the event loop') self.loop.stop() def find_next(self, data): index = self.word_list.index(data) return self.word_list[index + 1] loop = asyncio.get_event_loop() coro = loop.create_connection(lambda: EchoClientProtocol(loop), '127.0.0.1', 8888) loop.run_until_complete(coro) loop.run_forever() loop.close()