thomasdola

thomasdola

Hey guys first post here!
It seems that I’m missing something because I can’t get this problem to work.

I have a simple controller when hit broadcast a welcome message to clients using Endpoint.broadcast!() function.
But event broadcast from my controller using the Endpoint does not seem to hit clients.
I even run test on the controller and they are failing…

What is confusing me is when i broadcast the same in my channel with both Channel.broadcast() and Endpoint.broadcast!() , the event hits the clients…

My Controller

defmodule RealTimeWeb.PageController do
  use RealTimeWeb, :controller

  def index(conn, _params) do
    RealTimeWeb.Endpoint.broadcast!("PAGE", "WELCOME", %{data: "Welcome to Real Time Page"})
    render(conn, "index.html")
  end
end

My Controller Test => Failed

defmodule RealTimeWeb.PageControllerTest do
  use RealTimeWeb.ConnCase

  test "GET /", %{conn: conn} do
    conn = get(conn, "/")
    assert_receive %Phoenix.Socket.Broadcast{event: "WELCOME", topic: "PAGE", payload: %{"data" => _}}
    #assert html_response(conn, 200) =~ "Welcome to Phoenix!"
  end
end

My Channel

defmodule RealTimeWeb.PageChannel do
    use RealTimeWeb, :channel

    @topic "PAGE"

    def join(@topic = topic, params, socket), do: _join(params, topic, socket)
    def join(_, _, _), do: {:error, %{reason: "unauthorized"}}

    defp _join(_params, topic, socket) do
        send(self(), {:after_join, topic})
        {:ok, socket}
    end

    def handle_info({:after_join, @topic}, socket) do
        broadcast!(socket, "WELCOME", %{data: "welcome to Real Time Channel"})
        RealTimeWeb.Endpoint.broadcast(@topic, "WELCOME", %{data: "Welcome to Real Time Channel with endpoint"})
        {:noreply, socket}
    end
end

My Channel Test => Passed

defmodule RealTimeWeb.PageChannelTest do
    use RealTimeWeb.ChannelCase
    alias RealTimeWeb.UserSocket

    setup do
        {:ok, socket} = connect(UserSocket, %{})
        {:ok, socket: socket}
    end

    test "send welcome message when join topic successfully", %{socket: socket} do
        {:ok, _, _socket} = subscribe_and_join(socket, "PAGE", %{})

        assert_broadcast "WELCOME", %{data: _}
    end

end

My Socket

defmodule RealTimeWeb.UserSocket do
  use Phoenix.Socket

  ## Channels
  channel "PAGE", RealTimeWeb.PageChannel

  def connect(_params, socket, _connect_info) do
    {:ok, socket}
  end

  def id(_socket), do: nil
end

Client side (Socket.js)


import {Socket} from "phoenix"

let socket = new Socket("/socket", {params: {token: window.userToken}})

socket.connect()

let channel = socket.channel("PAGE", {})

channel.on("WELCOME", data => console.log(data))

channel.join()
  .receive("ok", resp => { console.log("Joined successfully", resp) })
  .receive("error", resp => { console.log("Unable to join", resp) })

export default socket

I really need your help…
Thank you..

Showing Posts 1 to 10

hubertlepicki

hubertlepicki

Is your problem only test-related, or does it also not work when you start the app, open browser, trigger some action - in that case do you get the broadcast sent to clients?

thomasdola

thomasdola OP

Also browser related…

Only events broadcasted from Channel Module is hitting the browser…
Not The ones being broadcasted from the Controller Module…

rjk

rjk

just created a new phx app from scratch and copy pasted in your code. For me it worked fine (also the broadcast from the controller). I can see all messages inside the browsers dev console.
The only change on top of your code was uncommenting this line in app.js:

import socket from "./socket"

with these kind of issues I would advise to create a public github project with your whole project inside, in that way people can help you better and you talk about the exact same code (bit by bit).

thomasdola

thomasdola OP

Dont have access at the moment ..
I ll upload the whole demo to github and link so that u can have a look at it…

Thank you..

chrismccord

chrismccord

Creator of Phoenix

You need to subscribe your test process in your controller test to the topic you are broadcasting to:

RealTimeWeb.Endpoint.subscribe("PAGE")
hubertlepicki

hubertlepicki

That’s why I asked if it’s only test-related issue. But the author claims it’s happening outside tests too.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

@hubertlepicki Sure, but the fact remains that if they want to make the test work they need to join the channel within the test.

hubertlepicki

hubertlepicki

You, sir, make a lot of sense

thomasdola

thomasdola OP

this is a link to the github project…
RealTime

thomasdola

thomasdola OP

Changed the controller test to this…

defmodule RealTimeWeb.PageControllerTest do
  use RealTimeWeb.ConnCase

  setup do
    RealTimeWeb.Endpoint.subscribe("PAGE")
  end

  test "GET /", %{conn: conn} do
    conn = get(conn, "/")
    assert_receive %Phoenix.Socket.Broadcast{event: "WELCOME", topic: "PAGE", payload: %{"data" => _}}
    assert html_response(conn, 200) =~ "Welcome to Phoenix!"
  end
end

And it passed successfully.

Yet am still not receiving the “WELCOME” event in my client side…


import {Socket} from "phoenix"

let socket = new Socket("/socket", {params: {token: window.userToken}})

socket.connect()

let channel = socket.channel("PAGE", {})

channel.on("WELCOME", data => console.log(data))

channel.join()
  .receive("ok", resp => { console.log("Joined successfully", resp) })
  .receive("error", resp => { console.log("Unable to join", resp) })

export default socket

Am supposed to have 3 console log, but only 2 displaying…

These are event are hitting the client side (Being broadcasted from RealTime.PageChannel)

def handle_info({:after_join, @topic}, socket) do
        broadcast!(socket, "WELCOME", %{data: "welcome to Real Time Channel"})
        RealTimeWeb.Endpoint.broadcast(@topic, "WELCOME", %{data: "Welcome to Real Time Channel with endpoint"})
        {:noreply, socket}
end

But the following no hitting the client side (Being broadcasted from RealTime.PageController)

def index(conn, _params) do
    RealTimeWeb.Endpoint.broadcast!("PAGE", "WELCOME", %{data: "Welcome to Real Time Page"})
    render(conn, "index.html")
end

Console Log

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New
dillonoconnor
Is there any way to avoid the Hologram compiler running when using iex? It seems like the front-end code could potentially be disregarded...
New
thiagogsr
** (ArgumentError) expected :max_attempts to be a positive integer, got: {:@, [line: 10, column: 19], [{:max_attempts, [line: 10, column:...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews