以下是一个简单的Python WebSocket服务器示例:

import asyncio
import websockets

async def handle(websocket, path):
    async for message in websocket:
        await websocket.send(message)

start_server = websockets.serve(handle, 'localhost', 8765)

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

这个服务器会接收客户端发送的消息,并将相同的消息发送回客户端。服务器监听在本地主机的8765端口上。

要运行此服务器,您需要安装 websockets 库。可以使用以下命令安装该库:

pip install websockets

运行服务器后,您可以使用WebSocket客户端连接到它,并发送/接收消息。以下是一个简单的Python WebSocket客户端示例:

import asyncio
import websockets

async def hello():
    async with websockets.connect('ws://localhost:8765') as websocket:
        await websocket.send('Hello, server!')
        response = await websocket.recv()
        print(response)

asyncio.get_event_loop().run_until_complete(hello())

这个客户端将发送 "Hello, server!" 消息给服务器,并打印服务器返回的响应消息。

希望这个示例能帮助您开始使用Python编写WebSocket服务器

python websocket服务端

原文地址: http://www.cveoy.top/t/topic/ifDD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录