websocket封装
在Python中,可以使用websockets
库来封装WebSocket。以下是一个简单的WebSocket服务器和客户端的例子。
首先,安装websockets
库:
pip install websockets
服务器端代码:
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
await websocket.send(message)
start_server = websockets.serve(echo, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
客户端代码:
import asyncio
import websockets
async def hello():
async with websockets.connect('ws://localhost:8765') as websocket:
await websocket.send('Hello World!')
response = await websocket.recv()
print(f'Received: {response}')
asyncio.get_event_loop().run_until_complete(hello())
在这个例子中,服务器端监听8765端口,并将接收到的消息原样发送回客户端。客户端连接到服务器,发送一条消息,然后等待并打印服务器响应的消息。
评论已关闭