Websocket messages sent to multiple clients are not being received

I’m making a multiplayer game and I’m making the multiplayer its own package. In my server class, I have a broadcast method and a send_to_all_except method. The problem I’m having it that the messages are not being sent properly (the messages are not being received by the client(s)). Both methods are pretty much identical except for the client_websockets list so I’ll only put the code for broadcast here.

def broadcast(self, msg):
    client_websockets = [client.ws for client in self.clients]
    for ws in client_websockets:
        asyncio.create_task(self._send(ws, msg))

I know that client_websockets is not empty when running it so that’s not the problem. This is how it is done in the websockets documentation.

The code for _send is very simple and is shown below.

async def _send(self, ws, msg):
    try:
        await ws.send(msg)
    except websockets.ConnectionClosed:
        self.clients.remove([client for client in self.clients if client.ws == ws])

I have tried using asyncio.create_task() as in the code above and asyncio.ensure_future() but neither work.

All code is on GitHub.

I asked this exact question on Stack Overflow, but I got no responses and a downvote. My questions always seem to be frowned upon on there. Any feedback on why that might be would be appreciated.

Thanks!

Because StackOverflow. The site’s pretty awful for asking questions on.

This looks a bit odd though:

self.clients.remove([client for client in self.clients if client.ws == ws])

I wonder if it’d be easier to just pass the client object, rather than the socket.

async def _send(self, cli, msg):
    try:
        await cli.ws.send(msg)
    except websockets.ConnectionClosed:
        self.clients.remove(client)

def broadcast(self, msg):
    for cli in self.clients:
        asyncio.create_task(self._send(cli, msg))

But that might break other things in your code - I haven’t looked.

Refer to: How to create a Minimal, Reproducible Example - Help Center - Stack Overflow

1 Like