JavaScript Client
Let’s have a look at the JavaScript client messages in depth.
Receiving messages with the JavaScript client
A Channel can send messages to a connected client at any time, not just in response to an incoming message. We coded this earlier in our PingChannel
with handle_out/3
. We’ll leverage this message to request that the connected client sends us a ping
.
// hello_sockets/assets/js/socket.jschannel.on("send_ping", (payload) => {console.log("ping requested", payload)channel.push("ping").receive("ok", (resp) => console.log("ping:", resp.ping))})
The callback of our client channel is used to register incoming message subscriptions. The first argument is the string name of the event that we want to handle; this requires us to know the exact event name for incoming messages. For this reason, it is a good idea not to use dynamic event names. We can instead place dynamic information in the message payload.
iex -S mix phx.serveriex(1)> HelloSocketsWeb.Endpoint.broadcast("ping", "request_ping", %{}):ok
As we did earlier, we use the broadcast/3
function to request a ping
from our Channel. This will cause a message to be pushed to all connected clients on the ping
topic. Our handle_out
function changes the original ...