How to start iex with the environment variable for the PORT of the ListenSocket

436 Views Asked by At

I have created a server and a client part for my application and I want to start each node with different port, I want to do it with environment variable how is it possible? here is the server code :

 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

and the client connection code :

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

and the full code is here

1

There are 1 best solutions below

4
Aleksei Matiushkin On

You are looking for System.get_env/2.

For instance, you might amend Multichat.Server.accept/1 function to somewhat like:

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