使用 Simple Protocol
asyncio.BaseProtocol 類是asyncio模塊中協(xié)議接口(protocol interface)的一個(gè)常見的基類。asyncio.Protocolclass 繼承自asyncio.BaseProtocol 并為stream protocols提供了一個(gè)接口。下面的代碼演示了asyncio.Protocol 接口的一個(gè)簡(jiǎn)單實(shí)現(xiàn),它的行為1就像一個(gè)echo server,同時(shí),它還會(huì)在Python的控制臺(tái)中輸出一些信息。SimpleEchoProtocol 繼承自asyncio.Protocol,并且實(shí)現(xiàn)了3個(gè)方法:connection_made, data_received 以及 andconnection_lost:
import asyncio class SimpleEchoProtocol(asyncio.Protocol): def connection_made(self, transport): """ Called when a connection is made. The argument is the transport representing the pipe connection. To receive data, wait for data_received() calls. When the connection is closed, connection_lost() is called. """ print("Connection received!") self.transport = transport def data_received(self, data): """ Called when some data is received. The argument is a bytes object. """ print(data) self.transport.write(b'echo:') self.transport.write(data) def connection_lost(self, exc): """ Called when the connection is lost or closed. The argument is an exception object or None (the latter meaning a regular EOF is received or the connection was aborted or closed). """ print("Connection lost! Closing server...") server.close() loop = asyncio.get_event_loop()server = loop.run_until_complete(loop.create_server(SimpleEchoProtocol, 'localhost', 2222))loop.run_until_complete(server.wait_closed())
你可以通過運(yùn)行一個(gè)telnet客戶端程序,并且連接到localhost的2222端口來測(cè)試這個(gè)echo server。如果你正在使用這個(gè)端口,你可以將這個(gè)端口號(hào)修改為任何其他可以使用的端口。如果你使用默認(rèn)的值,你可以在Python的控制臺(tái)中運(yùn)行上面的代碼,之后在命令提示符或終端中運(yùn)行 telnet localhost 2222。你將會(huì)看到 Connection received! 的信息顯示在Python的控制臺(tái)中。接下來,你在telnet的控制臺(tái)中輸入的任何字符都會(huì)以echo:跟上輸入的字符的形式展示出來,同時(shí),在Python的控制臺(tái)中會(huì)顯示出剛才新輸入的字符。當(dāng)你退出telnet控制臺(tái)時(shí),你會(huì)看到Connection lost! Closing server... 的信息展示在Python的控制臺(tái)中。
舉個(gè)例子,如果你在開啟telnet之后輸入 abc,你將會(huì)在telnet的窗口中看到下面的消息:
echo:abecho:bcecho:c
此外,在Python的控制臺(tái)中會(huì)顯示下面的消息:
Connection received! b'a' b'b' b'c' Connection lost! Closing server...
在創(chuàng)建了一個(gè)名為loop的事件循環(huán)之后,代碼將會(huì)調(diào)用loop.run_until_complete來運(yùn)行l(wèi)oop.create_server這個(gè)協(xié)程(coroutine)。這個(gè)協(xié)程創(chuàng)建了一個(gè)TCP服務(wù)器并使用protocol的工廠類綁定到指定主機(jī)的指定端口(在這個(gè)例子中是localhost上的2222端口,使用的工廠類是SimpleEchoProtocol)并返回一個(gè)Server的對(duì)象,以便用來停止服務(wù)。代碼將這個(gè)實(shí)例賦值給server變量。用這種方式,當(dāng)建立一個(gè)客戶端連接時(shí),會(huì)創(chuàng)建一個(gè)新的SimpleEchoProtocol的實(shí)例并且該類中的方法會(huì)被執(zhí)行。
新聞熱點(diǎn)
疑難解答
圖片精選