How to broadcast in controllers?

Hello.

I’d like to send a websocket event in controllers. I’ve created a debug function for broadcasting.

  def broadcast(conn, _params) do
    #PubSub.broadcast(Pappap.PubSub, "online", "force", "msg!")
    PappapWeb.Endpoint.broadcast("online", "force", "msg!")
    #OnlineChannel.broadcast_all("force", "messaaaaaage")

    json(conn, %{msg: "broadcast done"})
  end

It throws an error.

no function clause matching in Phoenix.Channel.Server.broadcast/4

I’ve tried the PubSub way as well, but it still throws an error,

no function clause matching in Phoenix.PubSub.broadcast/4

I don’t know what is wrong in this function…
I have seen these documents.

https://hexdocs.pm/phoenix/Phoenix.Endpoint.html#c:broadcast/3
https://hexdocs.pm/phoenix_pubsub/Phoenix.PubSub.html#broadcast/4

Help me!

The third argument to broadcast needs to be a map. Try: PappapWeb.Endpoint.broadcast("online", "force", %{message: "msg!"})

3 Likes

Thank you! Now I’m able to broadcast in a controller!

1 Like