有时有的接口提供的是websocket服务,在python中如何跟websocket进行交互呢?
首先我们需要用到 websockets 模块
安装代码:pip3 install websockets
下面提供一个简单的python与websocket交互代码:
import asyncio
import websockets
async def connect_to_server():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
# 发送消息
message = "Hello, WebSocket!"
await websocket.send(message)
print(f"Sent message: {message}")
# 接收服务器的响应
response = await websocket.recv()
print(f"Received response: {response}")
# 运行事件循环连接到WebSocket服务器
asyncio.get_event_loop().run_until_complete(connect_to_server())
上面代码接收到一次消息就会终止运行,如何想一直运行,要用到死循环执行获取是否有消息发过来。
import asyncio
import websockets
async def connect_to_server():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
# 发送消息
message = "Hello, WebSocket!"
await websocket.send(message)
print(f"Sent message: {message}")
await recv_data(websocket)
async def recv_data(websocket):
while True:
response = await websocket.recv()
print(f"Received response: {response}")
# 运行事件循环连接到WebSocket服务器
asyncio.get_event_loop().run_until_complete(connect_to_server())