I have EmployeeSocket
in Endpoint.ex like this
socket "/employee", MyAppWeb.EmployeeSocket,
websocket: true,
longpoll: false
And in emplyee_socket.ex
channel "store:*", MyAppWeb.StoreChannel
And also doing some authentication in connect
function to let only employee join StoreChannel
If i get a new order from customer, I want to broadcast a message to StoreChannel
to notify
employees about new order.
So I just tested code like this
In store_channel.ex
@impl true
def handle_in("new_order", payload, socket) do
IO.puts("Incoming new order")
{:noreply, socket}
end
then tried in iex console
MyAppWeb.Endpoint.broadcast!("store:1", "new_order", %{message: "some message"})
:ok
I expected to see a message “Incoming new order”
But I don’t see any message.
What am I missing?
handle_in
deals with messages coming into the system from connected clients. broadcast
sends messages to connected clients. So to have your channel be aware of those you need to implement handle_out
and disable fasttracking, which optimizes broadcasts to not involve the channel process. This can be done by using intercept
for the message if you can live with the performance loss of doing that.
1 Like
Oh I missed this point.
So I tried to intercept outgoing event in channel using handle_out to see if it catches
intercept ["new_order"
@impl true
def handle_out("new_order", message, socket) do
IO.puts("New order message sending out")
{:noreply, socket}
end
And it still doesn’t work.
There is no “New order message sending out” is printed in server log.
The problem is that I was running broadcast function in iex -S mix session. That is why I didn’t get a message.
I tried iex -S mix phx.server. it works!