Skip to content

Instantly share code, notes, and snippets.

@msantos
Created July 25, 2015 14:22
Show Gist options
  • Save msantos/fb0accb7ce0d2e657f86 to your computer and use it in GitHub Desktop.
Save msantos/fb0accb7ce0d2e657f86 to your computer and use it in GitHub Desktop.
-module(iecho).
-include_lib("procket/include/procket.hrl").
-export([listen/0, listen/1]).
%%%
%%% Warning: error handling omitted, leaks fd's on error
%%%
listen() ->
listen(0).
listen(Port) ->
ok = inert:start(),
{ok, Socket} = procket:socket(inet, stream, 0),
Sockaddr = <<
(procket:sockaddr_common(procket:family(inet), 16))/binary,
Port:16, % Port
0,0,0,0, % IPv4 ANY address
0:64
>>,
BACKLOG = 1024,
ok = procket:bind(Socket, Sockaddr),
ok = procket:listen(Socket, BACKLOG),
{ok, <<_:16, ListenPort:16, _/binary>>} = procket:getsockname(Socket, Sockaddr),
error_logger:info_report([{listening, ListenPort}]),
accept(Socket).
accept(Listen) ->
{ok,read} = inert:poll(Listen),
{ok, Socket} = procket:accept(Listen),
spawn(fun() -> echo(Socket) end),
accept(Listen).
accept(Listen) ->
{ok,read} = inert:poll(Listen),
{ok, Socket} = procket:accept(Listen),
spawn(fun() -> echo(Socket) end),
accept(Listen).
echo(Socket) ->
{ok,read} = inert:poll(Socket),
case procket:read(Socket, 16#ffff) of
{ok, <<>>} ->
ok = procket:close(Socket),
ok;
{ok, Buf} ->
{ok,write} = inert:poll(Socket, [{mode, write}]),
ok = procket:write(Socket, Buf),
echo(Socket)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment