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.

Phoenix.Endpoint — Phoenix v1.7.10
Phoenix.PubSub — Phoenix.PubSub v2.1.3

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