Phoenix websocket: how to send message to one user

Tags: #<Tag:0x00007f11421a1b48> #<Tag:0x00007f11421a19e0>


I’m new to Phoenix and I’m following this tutorial to implement something similar to chat application as described in that tutorial.
That article talks about how to broadcast a message, I want to send a message to a particular user. And I couldn’t find something similar to send. How I can do that.
Also, to do this, do I have to save all the connected socket objects in another process’s state, maybe using a map which maps username -> socket.


One way to do it would be to subscribe your users to a particular topic individual to each one of them. Then you would have a way of sending particular messages to them using that topic and simply broadcasting to it, effectively working as if you were “sending” them a message. Of course this only accounts for when the receiving user is online and subscribed to his own topic.


Thanks, this should work.
How costly/cheap is creating a topic?


AFAIK the phoenix team is not yet charging for creating topics, so it’s free.


The cost will probably be one entry with one term in an ETS table? How that translates into “really” useful information I’m not sure.


The trick is to broadcast to a specific user with

socket.endpoint.broadcast!(“user:#{id}”, message, payload)


Quite cheap, I wouldn’t worry about it at this point.