user10186746
user10186746

Reputation: 11

How can I listen multiple ports via Elixir?

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?

Upvotes: 1

Views: 421

Answers (1)

Patrick Oscity
Patrick Oscity

Reputation: 54674

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.

Upvotes: 3

Related Questions