Python websockets wait for a response

Viewed 287

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.

1 Answers

Try this example:

server.py (server waits for msg1 and msg2 and responds accordingly):

async def runServer():
    server = await websockets.serve(onConnect, "localhost", port=8765)
    print("Server started listening to new connections...")
    await server.wait_closed()


async def onConnect(ws):
    try:
        while True:
            message = await ws.recv()

            if message == "msg1":
                await ws.send("response from server 1")
            elif message == "msg2":
                await ws.send("response from server 2")
    except websockets.exceptions.ConnectionClosedOK:
        print("Client closed...")


if __name__ == "__main__":
    asyncio.run(runServer())

client.py (first sends msg1, prints response and afterwards sends msg2 and prints response):

async def connect():
    async with websockets.connect(
        "ws://localhost:8765",
    ) as ws:

        print("Connected to the switch.")

        await ws.send("msg1")
        response = await ws.recv()

        print("Response from the server:", response)

        await ws.send("msg2")
        response = await ws.recv()

        print("Response from the server:", response)


if __name__ == "__main__":
    asyncio.run(connect())

The clients prints:

Connected to the switch.
Response from the server: response from server 1
Response from the server: response from server 2
Related