Elm、phoenix 和 elixir 对我来说很新,所以我想我会制作频道测试应用程序简单的示例应用程序来测试凤凰频道的使用。该应用程序还包含其他内容,因为它是由旧的“部件”制成的,但请耐心等待。
这个想法是你有几个 genservers 对 phoenix 端点进行 http 调用。基本上,他们只是在更新代理进程中保存的列表。该列表通过凤凰频道显示在 Elm 应用程序中。目标只是看看如果代理状态通过多个进程频繁更新会发生什么。
这就是我到目前为止所拥有的。我有一个带有 Elm 应用程序设置的凤凰网站和一个单独的 Elixir 应用程序,其中 genservers 进行更新。一切正常大约 20 秒,但随后通道连接被切断并且不会重新建立,除非我在浏览器上点击刷新。我可以从日志中看到后端仍然工作正常,并且浏览器控制台上也没有错误。那么这里的交易是什么?我认为通道连接如果丢失应该自动重新连接,为什么它仍然断开连接?
我猜问题出在elm-phoenix-socket上。这是在 elm 应用程序中设置的:
socketServer : String
socketServer =
"ws://localhost:4000/socket/websocket"
initPhxSocket : Phoenix.Socket.Socket Msg
initPhxSocket =
Phoenix.Socket.init socketServer
|> Phoenix.Socket.withDebug
|> Phoenix.Socket.on "new:heartbeats" "heartbeats:lobby" ReceiveHeartbeats
以下是在后端进行广播的方式:
defmodule AbottiWeb.ApiController do
use AbottiWeb.Web, :controller
def index(conn, _params) do
beats = AbottiWeb.HeartbeatAgent.get()
json conn, beats
end
def heartbeat(conn, %{"agent" => agent} ) do
AbottiWeb.HeartbeatAgent.update(agent)
beats = AbottiWeb.HeartbeatAgent.get()
AbottiWeb.Endpoint.broadcast("heartbeats:lobby", "new:heartbeats", beats)
json conn, :ok
end
end
所以本质上,genservers 不断地调用那个心跳端点。我怀疑问题出在这里。问题所在的另一种可能性是通道设置,如下所示:
user_socket.ex:
defmodule AbottiWeb.UserSocket do
use Phoenix.Socket
channel "heartbeats:*", AbottiWeb.HeartbeatChannel
transport :websocket, Phoenix.Transports.WebSocket
def connect(_params, socket) do
{:ok, socket}
end
def id(_socket), do: nil
end
和 heartbeat_channel.ex:
defmodule AbottiWeb.HeartbeatChannel do
use AbottiWeb.Web, :channel
require Logger
def join("heartbeats:lobby", payload, socket) do
Logger.debug "Hearbeats:lobby joined: #{inspect payload}"
if authorized?(payload) do
{:ok, socket}
else
{:error, %{reason: "unauthorized"}}
end
end
# Channels can be used in a request/response fashion
# by sending replies to requests from the client
def handle_in("ping", payload, socket) do
{:reply, {:ok, payload}, socket}
end
# It is also common to receive messages from the client and
# broadcast to everyone in the current topic (heartbeats:lobby).
def handle_in("shout", payload, socket) do
broadcast socket, "shout", payload
{:noreply, socket}
end
# This is invoked every time a notification is being broadcast
# to the client. The default implementation is just to push it
# downstream but one could filter or change the event.
def handle_out(event, payload, socket) do
Logger.debug "Broadcasting #{inspect event} #{inspect payload}"
push socket, event, payload
{:noreply, socket}
end
# Add authorization logic here as required.
defp authorized?(_payload) do
true
end
end
那么任何想法是什么问题?我猜这真的很简单。
好的,我现在知道套接字传输超时了。但它为什么这样做呢?