未定义的函数发送/ 3

时间:2016-10-18 22:40:49

标签: elixir phoenix-framework

我正在尝试在套接字路由器中侦听消息,向内存进程发送消息,生成Runner模块,然后将结果广播到客户端。

在凤凰城以外的独立测试中,此代码有效。有了Phoenix,我收到了这个错误

~/chatroom:.mix phoenix.server
Compiling 2 files (.ex)

== Compilation error on file web/models/runner.ex ==
** (CompileError) web/models/runner.ex:8: undefined function send/3
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
    (elixir) lib/kernel/parallel_compiler.ex:117: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1

我的lobby_channel.ex:

defmodule Chatroom.LobbyChannel do
  require Runner
  use Phoenix.Channel

  {:ok, pid: spawn(fn -> Runner.input() end)}

  def join("lobby", _payload, socket) do
    {:ok, socket}
  end

  def handle_in("new_message", payload, socket) do
    case payload["message"] do
      "hello" -> broadcast! socket, "new_message", payload
      "jump" -> send pid, {:jump, self, [avatar: avatar, socket: socket]}
      _ -> nil
    end

    {:noreply, socket}
  end

  receive do
    {:result, mover, socket} -> broadcast! socket, "new_message", [name: "State", message: "5"]
  end
end

Runner.ex,存储在web / models / runner.ex

defmodule Runner do
    def spawn do
        %{maxJump: 100}
    end

    def input do
      receive do
       {:run, sender, data} -> send sender, run(sender[:avatar]), data[:socket]
       {:jump, sender, data} -> send sender, jump(sender[:avatar]), data[:socket]
     end

     input
    end

    defp run(mover) do
      mover = case mover.y do 
        1 ->
          Map.merge(mover, %{y: 0})
        _ -> mover
      end

        Map.merge(mover, %{x: mover.x + 1})
    end

    defp jump(mover) do
        case {mover.y} do
          {0} ->
            Map.merge(mover, %{y: mover.y + 1})
          _ ->
            mover
        end
    end
end

为什么我不能发送这些消息?

1 个答案:

答案 0 :(得分:2)

此表达式中发生错误,该表达式使用三个参数调用函数send

send sender, run(sender[:avatar]), data[:socket]

但是the send function只接受两个参数:发送内容的过程和要发送的消息。也许你想把这两个项目嵌入元组?像这样:

send sender, {run(sender[:avatar]), data[:socket]}

有一个send函数,它有三个参数,即Process.send/3。它的第三个参数是选项列表。您必须明确指定模块名称才能调用它。