Python搭建websocket服务

推荐使用python3.6以上版本来运行websockets

pip3 install websockets

主要用到的API有:

websockets.connect()
websockets.send()
websockets.recv()

server.py,用于搭建webscocket服务器,在本地8765端口启动,接收到消息后会在原消息前加上I got your message:再返回去。

import asyncio
import websockets


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


asyncio.get_event_loop().run_until_complete(websockets.serve(echo, 'localhost', 8765))
asyncio.get_event_loop().run_forever()

client.py

#!/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://localhost:8765'))

先执行server.py,然后执行client.pyclient.py的输出结果如下:

< Hello world!
> I got your message: Hello world!
> 2021-03-03 15:11:50

客户端发送了第一条消息给服务端,服务端接收到后发送了第二条消息,最后一条消息是由服务端主动发送给客户端的。

参考:搭建websocket服务

posted @ 2021-03-08 16:01  Sincere_Ye  阅读(13535)  评论(2编辑  收藏  举报