erlang 如何使用ListenSocket的PORT环境变量启动iex

1hdlvixo  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(151)

我已经为我的应用程序创建了一个服务器和一个客户端部分,我想用不同的端口启动每个节点,我想用环境变量来做这件事怎么可能?下面是服务器代码:

defmodule Multichat.Server do
  require Logger

  def accept(port) do
    {:ok, socket} = :gen_tcp.listen(port, [:binary, packet: :line, active: true, reuseaddr: true])
    Logger.info "Accepting connections on port #{port}"
    loop_acceptor(socket)
  end

  defp loop_acceptor(socket) do
    {:ok, client} = :gen_tcp.accept(socket)
    {:ok, pid} = DynamicSupervisor.start_child(Multichat.Server.ConnectionSupervisor, {Multichat.ClientConnection, client})
    :ok = :gen_tcp.controlling_process(client, pid)
    loop_acceptor(socket)
  end
end

和客户端连接代码:

defmodule Multichat.ClientConnection do
  use GenServer

  def start_link(socket), do: GenServer.start_link(__MODULE__, socket)
  def init(init_arg) do
    {:ok, init_arg}
  end

  def handle_call({:send, message}, _from, socket) do
    :gen_tcp.send(socket, message)
    {:reply, :ok, socket}
  end

  def handle_info({:tcp, _socket, message}, socket) do
    for {_, pid, _, _} <- DynamicSupervisor.which_children(Multichat.Server.ConnectionSupervisor) do
      if pid != self() do
        GenServer.call(pid, {:send, message})
      end
    end

    {:noreply, socket}
  end
end

完整的代码是here

nkhmeac6

nkhmeac61#

您正在寻找System.get_env/2
例如,您可以将Multichat.Server.accept/1函数修改为类似于:

def accept(port \\ nil)

def accept(nil) do
  "MY_PORT"
  |> System.get_env("6789")
  |> String.to_integer()
  |> accept()
end

def accept(port) do
  {:ok, socket} = :gen_tcp.listen(port, [:binary, packet: :line, active: true, reuseaddr: true])
  Logger.info "Accepting connections on port #{port}"
  loop_acceptor(socket)
end

相关问题