我是 Elixir 的初学者。
我有一个多人游戏的长生不老药应用程序,它只是将接收到的命令复制到连接到通道的所有玩家。这是可行的,但在复制接收到的命令时会有一些延迟。消除延迟问题的最佳选择是什么?
为了将命令复制到连接到频道的所有播放器,我使用广播功能。这是最好的功能吗?
见以下代码:
defmodule GameWeb.GameChannel do
use GameWeb, :channel
alias Game.GameState
alias Game.Error
# join to topic game:*
def join("game:" <> code, %{"email" => email}, socket) do
case Map.has_key?(GameState.games(), code) do
true ->
socket = assign(socket, :player, 2)
game =
code
|> GameState.get_game()
|> Map.put(:player2, %{:email => email, :score => 0})
|> GameState.update_game()
socket = assign(socket, :game, game)
{:ok, game, socket}
false ->
socket = assign(socket, :player, 1)
game =
GameState.create_game(code)
|> Map.put(:player1, %{:email => email, :score => 0})
|> GameState.update_game()
socket = assign(socket, :game, game)
{:ok, game, socket}
end
end
# topic not found
def join(_topic, _payload, _socket) do
{:error, Error.get(:resource_not_found)}
end
def handle_in("playerAction", payload, socket) do
broadcast!(socket, "playerAction", Map.put(payload, :from_player, socket.assigns.player))
{:noreply, socket}
end
end