pythonwebsocket

How to filter out empty websocket messages in Python?


Why does this keep printing emptiness? I can't seem to be able to filter out the empty messages. See, I am even printing the lengnth of the message and still get sheer emptiness printed.

    while True:
        try:
            async with websockets.connect('ws://localhost:8765') as websocket:
                msg= await asyncio.wait_for(websocket.recv(),.1)
                if msg:
                    print(len(msg))
                    terminal.text_area.insert(tk.END, msg)
        except Exception as e:
            print(e)
        app.update()

In the debugger I can see that msg is a webscoket message object blabla but can't do anything with it when it's empty. No length, no printable thing, not castable to False, not equal to ''. Even the .str() is not equal to ''.


Solution

  • I think that an additional layer of checks can be added by checking if the WebSocket server closes the connection or sends an empty message, websocket.recv() will return 'None'. You can check for this case and skip processing the message if it's 'None'.

    while True:
        try:
            async with websockets.connect('ws://localhost:8765') as websocket:
                msg = await asyncio.wait_for(websocket.recv(), .1)
                if msg is not None:  # Check if msg is not None
                    print(len(msg))
                    terminal.text_area.insert(tk.END, msg)
        except Exception as e:
            print(e)
        app.update()