1

I'd like to listen 2 ports via Elixir. I managed to listen the ports, though. However, I can't get data from second port.

  def accept() do
    {:ok, socket} = :gen_tcp.listen(7777, [:binary, packet: 0, active: false, reuseaddr: true])

    {:ok, httpSocket} =
      :gen_tcp.listen(8787, [:binary, packet: 0, active: false, reuseaddr: true])

    http_loop_acceptor(httpSocket)
    loop_acceptor(socket)
  end

  defp http_loop_acceptor(socket) do
    {:ok, client} = :gen_tcp.accept(socket)
    pid = spawn(fn -> http_serve(client) end)
    :ok = :gen_tcp.controlling_process(client, pid)
    http_loop_acceptor(socket)
  end

  defp loop_acceptor(socket) do
    {:ok, client} = :gen_tcp.accept(socket)
    pid = spawn(fn -> serve(client) end)
    :ok = :gen_tcp.controlling_process(client, pid)
    loop_acceptor(socket)
  end

I can send the data to 8787 port (httpSocket). However, I can't send any data to 7777 (socket).

If change the order of these 2 lines then I can send the data to 7777 (socket), I can't send any data to 8787 port.

http_loop_acceptor(httpSocket)
loop_acceptor(socket)

How can I listen multiple ports and receive data via those ports?

1 Answers1

3

In your accept function, the call to http_loop_acceptor will recurse infinitely, which means that loop_acceptor is never called.

If you want to listen on two sockets, you need to start two separate processes, one for each socket. A quick and dirty way is to use spawn, but in a real application you would model these processes as part of your supervision tree.

Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
  • This is one of the hardest things to wrap ones head around when first coming over to Erlang/Elixir. It took me way to long to think like this. – SudoKid Aug 07 '18 at 17:46