mac 搭建websocket

2022-01-18  本文已影响0人  sws1314

mac 搭建websocket

pip3 install websockets

服务端:

import asyncio
import websockets


async def echo(websocket, path):
    async for message in websocket:
        message = "I got your message: {}".format(message)
        print(message)
        await websocket.send(message)


asyncio.get_event_loop().run_until_complete(websockets.serve(echo, '0.0.0.0', 8282))
asyncio.get_event_loop().run_forever()

客户端:

#!/usr/bin/env python
import asyncio
import websockets

async def hello(uri):
    async with websockets.connect(uri) as websocket:
        await websocket.send("hello world")
        print("< HELLO WORLD")
        while True:
            recv_text = await websocket.recv()
            print("> {}".format(recv_text))

asyncio.get_event_loop().run_until_complete(hello('ws://192.168.0.5:8282'))

上一篇 下一篇

猜你喜欢

热点阅读