各位大佬,我的需求是構建一對能實時收發訊息的websocket服務器和客戶端。
服務器在被客戶端連接后,每2秒發送一個心跳資料,并且實時接收資料,收到后反饋一個對應資料。
客戶端在連接后,每5秒發送一個請求給服務器,并且實時接收資料。
我的代碼如下:
import asyncio
import websockets
import time
async def recv_msg(ws):
while True:
print("listening")
recv_text = await ws.recv()
print(recv_text)
response_text = f"your submit context: {recv_text}"
await ws.send(response_text)
async def Heart(ws):
while True:
print("heart")
await ws.send(f"{time.time()}")
await asyncio.sleep(2)
async def main_logic(websocket, path):
print(websocket)
await recv_msg(websocket)
await Heart(websocket)
start_server = websockets.serve(main_logic, "172.30.18.200", 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
import asyncio
import websockets
async def send_msg(ws):
while True:
# _text = input("Send: > ")
_text = ""
if _text == "exit":
await ws.close(reason="user exit")
return False
_text = "hello"
await ws.send(_text)
asyncio.sleep(5)
async def recv_msg(ws):
while True:
recv_text = await ws.recv()
print(recv_text)
async def main_logic():
async with websockets.connect("ws://172.30.18.200:5678") as ws:
await send_msg(ws)
await recv_msg(ws)
asyncio.get_event_loop().run_until_complete(main_logic())
但我發現main函式里面只有第一個await能執行,我應該怎么修改。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/18215.html
上一篇:python運行cmdTypeError:__init__( ) missing 1 required positional argument :'units'
下一篇:匯編語言
