Skip to content

Instantly share code, notes, and snippets.

@peterwillcn
Forked from adnils/server.ex
Created August 11, 2020 16:37
Show Gist options
  • Save peterwillcn/b28fd1857cd4ae1091db44182c0dc345 to your computer and use it in GitHub Desktop.
Save peterwillcn/b28fd1857cd4ae1091db44182c0dc345 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