一個簡單的 Websocket

在這裡,我們使用 asyncio 製作一個簡單的 echo websocket。我們定義用於連線伺服器和傳送/接收訊息的協同程式。websocket 的通訊在 main 協程中執行,該協程由事件迴圈執行。此示例是從先前的帖子修改

import asyncio
import aiohttp

session = aiohttp.ClientSession()                          # handles the context manager
class EchoWebsocket:
    
    async def connect(self):
        self.websocket = await session.ws_connect("wss://echo.websocket.org")
        
    async def send(self, message):
        self.websocket.send_str(message)

    async def receive(self):
        result = (await self.websocket.receive())
        return result.data

async def main():
    echo = EchoWebsocket()
    await echo.connect()
    await echo.send("Hello World!")
    print(await echo.receive())                            # "Hello World!"

if __name__ == '__main__':
    # The main loop
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())