import asyncio
import websockets
# 服务器端接收客户端消息并返回
async def echo(websocket, path):
async for message in websocket:
print(f"Received message: {message}")
await websocket.send(f"Echo: {message}")
# 启动WebSocket服务器
async def main():
async with websockets.serve(echo, "localhost", 8765):
print("Server started on ws://localhost:8765")
await asyncio.Future() # 运行服务器直到手动停止
# 运行服务器
if __name__ == "__main__":
asyncio.run(main())
导入模块:
asyncio
:用于编写异步代码,支持并发操作。websockets
:用于创建和管理WebSocket连接。定义echo
函数:
echo
是一个异步函数,它接收来自客户端的消息并将其回显回去。async for message in websocket
用于监听客户端发送的消息,并通过await websocket.send()
将消息回传给客户端。启动WebSocket服务器:
websockets.serve(echo, "localhost", 8765)
创建一个WebSocket服务器,监听本地的8765端口。await asyncio.Future()
让服务器一直运行,直到手动停止。运行服务器:
asyncio.run(main())
来启动服务器。这个示例展示了如何使用Python创建一个简单的WebSocket服务器,该服务器可以接收客户端的消息并将其回显回去。
上一篇:python 随机数
下一篇:python main
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站