1

I'm beginner in Elixir.

I have an elixir application for a multiplayer game that simply replicates the received command to all players connected to the channel. This is work but have some latency when replicates the received command. what is the best option for remove latency problem?

For replicates the command to all players connected to the channel, i use the broadcast function. Is the best function for this?

See follow code:

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
Nuno_Coletiv
  • 367
  • 3
  • 16
  • 1
    How much is "some delay"? Are you running this on a single node or in a cluster? – Justin Wood Feb 12 '18 at 14:48
  • 1
    Sometimes some seconds :\ In my game i create one process Agent per game just for save the current status of the game. Single node. – Nuno_Coletiv Feb 12 '18 at 15:08
  • Is this application currently being run on your local machine, or is it hosted somewhere? – Justin Wood Feb 12 '18 at 16:54
  • 1
    Local machine. Why? – Nuno_Coletiv Feb 12 '18 at 17:20
  • 1
    If it were hosted someone else the latency you are seeing could be due to the network, especially if you are physically far away from where the application is being hosted. As for the reason it is slow to replicate, I am unsure. There is nothing that jumps out at me as being slow. – Justin Wood Feb 12 '18 at 17:25
  • 1
    @JustinWood thanks for answering. but when seeing for the code apparently is everything fine? if you have time please help me with this https://stackoverflow.com/questions/48705526 – Nuno_Coletiv Feb 12 '18 at 17:48

0 Answers0