How to get a channel to receive a message on the server in Phoenix Framework

I am currently learning Phoenix Framework and I have a little problem getting the handle_in method that fits my feed.

My javascript (technically it's typescript) looks like this:

let channel = this.socket.chan('rooms:lobby', {});

channel.join().receive('ok', channel => {
  console.log(`Joined the channel`);
});

// channel.on("feed", payload => {
//   console.log(`Message from server: ${payload.list}`);
// });

channel.push("new:msg", 'test message');

      

And the server side def looks like this:

def handle_in("new:msg", msg, socket) do
  IO.puts "Message from the client: #{msg}"

  {:noreply,socket  }
end

      

Does anyone know why my channel is not valid?

+3


source to share


2 answers


I just figured it out. It turns out that I did not initialize the socket properly in my javascript. Setting up the log in js was very helpful to find the problem:

this.socket.logger = (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) };
this.socket.connect({ user_id: "123" })

      



Also thanks for letting me know 16.0 was missing :)

+1


source


Do you have your socket and pipe logic configured on the server side? Also - which version of Phoenix are you using? In versions> 0.15.0 you should have something like this inlib/app/endpoint.ex

# lib/hello_phoenix/endpoint.ex
defmodule HelloPhoenix.Endpoint do
  use Phoenix.Endpoint

  socket "/socket", HelloPhoenix.UserSocket
  ...
end

      

Then the socket module:

# web/channels/user_socket.ex
defmodule HelloPhoenix.UserSocket do
  use Phoenix.Socket

  channel "rooms:*", HelloPhoenix.RoomChannel
  ...
end

      



Then you should have a channel module that looks like this:

defmodule HelloPhoenix.RoomChannel do
  use Phoenix.Channel

  def join("rooms:lobby", auth_msg, socket) do
    {:ok, socket}
  end
  def join("rooms:" <> _private_room_id, _auth_msg, socket) do
    {:error, %{reason: "unauthorized"}}
  end

  def handle_in("new_msg", %{"body" => body}, socket) do
    broadcast! socket, "new_msg", %{body: body}
    {:noreply, socket}
  end

  def handle_out("new_msg", payload, socket) do
    push socket, "new_msg", payload
    {:noreply, socket}
  end
end

      

You can read more about channels in the official guides: http://www.phoenixframework.org/v0.16.0/docs/channels

Also in 0.16.0 your JavaScript socket.chan

was renamed to socket.channel

. You can read about it in the Upgrade Guide

+3


source







All Articles