Skip to content

Instantly share code, notes, and snippets.

@adnils
Last active August 11, 2020 16:37
Show Gist options
  • Save adnils/5c91b51e97c792a7c9e5 to your computer and use it in GitHub Desktop.
Save adnils/5c91b51e97c792a7c9e5 to your computer and use it in GitHub Desktop.
Elixir TCP echo server
defmodule Echo.Server do
def start(port) do
tcp_options = [:binary, {:packet, 0}, {:active, false}]
{:ok, socket} = :gen_tcp.listen(port, tcp_options)
listen(socket)
end
defp listen(socket) do
{:ok, conn} = :gen_tcp.accept(socket)
spawn(fn -> recv(conn) end)
listen(socket)
end
defp recv(conn) do
case :gen_tcp.recv(conn, 0) do
{:ok, data} ->
:gen_tcp.send(conn, data)
recv(conn)
{:error, :closed} ->
:ok
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment