我正在尝试将 Phoenix Channel、Token和Presence模块结合在一起,以向我的 Phoenix 1.3 应用程序添加聊天功能。我无法让所有 3 个模块一起工作。最后一个错误是connection to websocket closed before handshake
. 现在,我没有收到任何错误,但它也没有连接到套接字。
我认为问题在于 player_socket.ex 中的“连接”功能。(我有一个播放器资源)。这是功能:
def connect(%{"token" => token}, socket) do
case Phoenix.Token.verify(socket, "player auth", token, max_age: @max_age) do
{:ok, player_id} ->
player = Repo.get!(Player, player_id)
{:ok, assign(socket, :current_player, player)}
{:error, _reason} ->
:error
end
end
我正在 app.html.eex 的元标记中签署令牌。<%= tag :meta, name: "channel_token", content: Phoenix.Token.sign(@conn, "player auth", :player_id) %>
然后在 lobby_channel.ex 我尝试加入频道:
def join("lobby:lobby", _params, socket) do
send(self(), :after_join)
{:ok, assign(socket, :player_id, :current_player)}
end
def handle_info(:after_join, socket) do
push socket, "presence_state", Presence.list(socket)
{:ok, _} = Presence.track(socket, socket.assigns.current_player, %{
online_at: inspect(System.system_time(:seconds))
})
{:noreply, socket}
end
我阅读了文档,但似乎无法弄清楚为什么我无法使用“current_player”连接到 websocket,以便我可以使用 Presence 显示谁在线以及玩家的姓名与他们的聊天消息相关联。非常感谢任何见解!我在这里有回购: https ://github.com/EssenceOfChaos/gofish
更新
我正在使用“current_player”插件将播放器结构存储在 conn 中作为“current_player.
%Plug.Conn{adapter: {Plug.Adapters.Cowboy.Conn, :...},
assigns: %{current_player: %Gofish.Accounts.Player{__meta__: #Ecto.Schema.Metadata<:loaded, "players">,
email: "example@aol.com", id: 6,
这是我更新后的 lobby_channel.ex:
def join("lobby:lobby", _params, socket) do
send(self(), :after_join)
{:ok, socket}
end
def handle_info(:after_join, socket) do
push socket, "presence_state", Presence.list(socket)
{:ok, _} = Presence.track(socket, socket.assigns.current_player.id, %{
username: socket.assigns.current_player.username,
online_at: inspect(System.system_time(:seconds))
})
{:noreply, socket}
end