Broadcast message to all connected users using websocket (Erlang, RabbitMQ, Websocket, Gen_bunny, Cowboy)

I am trying to integrate websocket chat using ERlang, Cowboy, Websocket and gen_bunny.

I can make them work independently.

Browser -> Cowboy websocket chat (Works) Erlang and RabbitMQ AMQP (Works)

Combining them together, I can receive a message from the browser to Cowboy and transfer it to RabbitMQ and return it again from RabbitMQ.

I can even reply to the message to the user who sent it. However, I want to send the message to all connected users.

In my understanding, Erlang will create a separate process for each user. So, how to transfer it to all connected users after I return the answer from RabbitMQ ??

+4
source share
3 answers

Take a look at the gproc project: https://github.com/uwiger/gproc

It has a Pub / Sub template that you can use to create the chat you were talking about.

From the gproc wiki:

subscribe(EventType) -> %% Gproc notation: {p, l, Name} means {(p)roperty, (l)ocal, Name} gproc:reg({p, l, {?MODULE, EventType}}). notify(EventType, Msg) -> Key = {?MODULE, EventType}, gproc:send({p, l, Key}, {self(), Key, Msg}). 
+1
source

Right. Cowboy creates a process for each connection that runs your WebSocket handler code. One approach is to have the websocket_init/3 registration function of the websocket_init/3 handler with the "translation" process (and unregister the websocket_terminate/3 ). Upon receiving a message from RabbitMQ, the broadcast process repeats the message to all registered WebSocket connections, which can receive it using the callback to the websocket_info/3 handler.

The broadcast process can use monitors to detect when the WebSocket handler dies, and automatically removes it from the registration list.

Thus, the life of the handler might look something like this:

  • websocket_init/3 is called after Cowboy completes the protocol update requested in init/3 (to WebSocket). From here, the client handler is registered using broadcast , the process of broadcasting messages.
  • As long as the connection remains open, the handler receives broadcast message messages in its websocket_info/3 , passing messages along with the client, returning {reply, {text, Message}, State} .
  • Upon completion, the handler removes broadcast from itself. If for some reason this does not work properly, broadcast stores monitors for all subscribers to receive notifications of their death.
+1
source

Each cowboy process gets its own rabbit lineup. Broadcasting will work with wildcard bindings. No explicit loop. You can make a subscription optional without tying it accordingly. See: How to configure the queue so that all subscribers receive messages - Rabbit MQ

0
source

All Articles