-
-
Save peterwillcn/b28fd1857cd4ae1091db44182c0dc345 to your computer and use it in GitHub Desktop.
Elixir TCP echo server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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