WebsocketHub - send message to a particular socket_id AND channel

I’m implementing websockets communication between server and client. I use an official example and broadcast works well. Now I have a user that subscribes to a channel and I want to send a message from the server to that user (not to all of them via broadcast) to the specific channel (means if user is not subscribed to it, but has a connection and being subscribed to other channels he won’t get this message).

I found two methods in nameko websocket.py:

  1. broadcast - uses channel, but not user specific
  2. unicast - seems like what I need but it does not have a channel parameter (only socket_id)

Is there a way I can do that? Or do I need to use unicast with some flag in the data object and parse it on the client? Are channels needed only for broadcasting here?

Thank you!

Unicast is what you want if you’re trying to send a message to a single user/socket. If you only want to send the message if a user is or is not already subscribed to a channel then just do a lookup in the channel subscriptions with the socket_id before you send.

Yeah, that’s the way I do, but it has two problems:

  • Clear db table (maybe it’s better to use redis but I don’t want to have it only for this purpose) is pain. Currently I have a cron job to do so in order not to perform DELETE on every unsubscribe event. And in that case if user unsubscribed from a channel (e.g. left the page that needs this subsciption) he will still get messages because socket_id is single for the user (since we have one connection).

  • As a consequence it has problems with front end part since it needs to resolve manually, which channel that message is for, based on message’s data body. Doesn’t look like a clear solution.

P.S. Thanks for the response!