Home > other >  Python coroutines async have multiple await in function, how to let them all to run
Python coroutines async have multiple await in function, how to let them all to run

Time:11-24

Dear bosses, I demand is to build a real-time websocket server and the client to send and receive messages,
Server after being a client connection, send a heartbeat data every 2 seconds, and receive data, real-time feedback after receiving a corresponding data,
After the client connection, every 5 seconds sends a request to the server, and receive real-time data,

My code is as follows:
 
The import asyncio
The import web sockets
The 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 the ws. Send (response_text)

Async def Heart (ws) :

While True:
Print (" heart ")
Await the ws. Send (f "{time. Time ()}")
Await asyncio. Sleep (2)


Async def main_logic (websocket, path) :

Print (websocket)
Await recv_msg (websocket)
Await Heart (websocket)


The start_server=web sockets. Serve (main_logic, "172.30.18.200", 5678)


Asyncio. Get_event_loop (.) run_until_complete (the start_server)
Asyncio. Get_event_loop (.) run_forever ()


 
The import asyncio
The import web sockets

Async def send_msg (ws) :
While True:
# _text=input (" Send: & gt;
")_text=""
If _text=="exit" :
Await the ws. Close (tiny="user exit")
Return False
_text="hello"
Await the 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 web sockets. Connect (ws://172.30.18.200: "5678") as the ws:

Await send_msg (ws)
Await recv_msg (ws)

Asyncio. Get_event_loop (.) run_until_complete (main_logic ())


But I found that the main function, only the first await can perform, how should I change,
  • Related