Skip to content

Instantly share code, notes, and snippets.

@msantos
Created July 25, 2015 14:23
Show Gist options
  • Save msantos/ba8c9e443da4058ac830 to your computer and use it in GitHub Desktop.
Save msantos/ba8c9e443da4058ac830 to your computer and use it in GitHub Desktop.
-module(xecho).
-export([listen/0, listen/1]).
listen() ->
listen(0).
listen(Port) ->
{ok, S} = gen_tcp:listen(Port, [binary, inet, {reuseaddr,true}, {backlog,1024}]),
io:format("Listening on: ~p~n", [inet:port(S)]),
accept(S).
accept(LS) ->
{ok, S} = gen_tcp:accept(LS),
Pid = spawn(fun() -> recv(S) end),
ok = gen_tcp:controlling_process(S, Pid),
accept(LS).
recv(S) ->
receive
{tcp, S, Data} ->
gen_tcp:send(S, Data),
recv(S);
{tcp_closed, S} ->
ok;
Error ->
error_logger:error_report([{socket, S}, {error, Error}])
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment