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…