在Python中,我正在为Websocket客户端使用“ websockets”库。
import asyncio
import websockets
async def init_sma_ws():
uri = "wss://echo.websocket.org/"
async with websockets.connect(uri) as websocket:
name = input("What's your name? ")
await websocket.send('name')
greeting = await websocket.recv()
问题是,一旦收到响应,客户端Websocket连接就会断开。我希望连接保持打开状态,以便以后可以发送和接收消息。
我需要进行哪些更改以保持websocket打开并以后能够发送和接收消息?
答案 0 :(得分:1)
我认为您的网络套接字由于recv()
之后退出上下文管理器而被断开了连接。
这样的代码可以完美地工作:
import asyncio
import websockets
async def init_sma_ws():
uri = "wss://echo.websocket.org/"
async with websockets.connect(uri) as websocket:
while True:
name = input("What's your name? ")
if name == 'exit':
break
await websocket.send(name)
print('Response:', await websocket.recv())
asyncio.run(init_sma_ws())