1 websockets安装

conda好像装不了,使用pip安装

pip install websockets

2 创建websocket服务器

使用以下代码创建一个简单的websocket服务器,服务器地址为:ws://localhost:5678/

# -*- coding: utf-8 -*-

import asyncio
import websockets

# 接收客户端消息并处理,这里只是简单把客户端发来的返回回去
async def recv_msg(websocket):
    while True:
        recv_text = await websocket.recv()
        response_text = f"Server receive message: {recv_text}"
        await websocket.send(response_text)


# 服务器端主逻辑
async def run(websocket, path):
    await recv_msg(websocket)

start_server = websockets.serve(run, 'localhost', 5678)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

3 使用在线工具测试

Python – 使用websockets库构建websocket服务器-StubbornHuang Blog