Reputation: 95
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
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