I'm trying to do a client/server with websockets and I want that when the client sends a message, it needs to wait to receive a response from the server. So the client can never send two messages in a row without a previous response.
I tried using Lock from asyncio but it doesn't work. Here's server.py:
async def runServer(self):
server = await websockets.serve(
self.onConnect,
"localhost",
port=8765
)
print("Server started listening to new connections...")
await server.wait_closed()
async def onConnect(self, ws):
try:
while True:
message = await ws.recv()
if message == "...":
...
And here is client.py
async def connect(self):
try:
lock = asyncio.Lock()
async with websockets.connect(
"ws://localhost:8765",
) as ws:
print("Connected to the switch.")
async with lock:
await ws.send("First message")
await ws.send("Second message")
while True:
message = await ws.recv()
print(f"Message received : {message}")
except Exception as e:
print(e)
And I would want the client to wait for a response from the first message and after that to send the second message.