leaf
leaf

Reputation: 95

TCP server not responding

I have the following TCP server written in Elixir utilizing the gen_tcp OTP module:

defmodule Test do
  def server() do
    {:ok, listen_sock} = :gen_tcp.listen(43594, [{:active, true}, :binary])
    {:ok, accept_sock} = :gen_tcp.accept(listen_sock)
    spawn(fn() -> poll(accept_sock) end)
  end

  defp poll(sock) do
    case :gen_tcp.recv(sock, 0, 20) do
      {:ok, data} ->
          IO.puts "#{data}"
          poll(sock)
      {:error, :closed} -> :ok
    end
  end
end

Test.server

As soon as I use telnet to connect to the server, it disconnects. Any idea as to what's going on?

Upvotes: 3

Views: 271

Answers (1)

bitwalker
bitwalker

Reputation: 9261

I would assume it's because server() is returning after spawn() is called and your application exits normally. I would write it like so:

defmodule Test do
  def server() do
    {:ok, listen_sock} = :gen_tcp.listen(43594, [{:active, true}, :binary])
    {:ok, accept_sock} = :gen_tcp.accept(listen_sock)
    poll(accept_sock)
  end

  defp poll(sock) do
    case :gen_tcp.recv(sock, 0, 20) do
      {:ok, data} ->
          IO.puts "#{data}"
          poll(sock)
      {:error, :closed} -> :ok
    end
  end
end

Test.server

I haven't tested the above code, but that should fix your problem.

Upvotes: 4

Related Questions