Skip to content

Instantly share code, notes, and snippets.

@infynyxx
Created July 8, 2014 22:35
Show Gist options
  • Save infynyxx/e97199f630f7dc2917b0 to your computer and use it in GitHub Desktop.
Save infynyxx/e97199f630f7dc2917b0 to your computer and use it in GitHub Desktop.
Concurrent erlang server
-module(erl_tcp).
-export([start_server/0, connect/1, recv_loop/1]).
-define(LISTEN_PORT, 9000).
-define(TCP_OPTS, [binary, {packet, raw}, {nodelay, true}, {reuseaddr, true}, {active, once}]).
start_server() ->
case gen_tcp:listen(?LISTEN_PORT, ?TCP_OPTS) of
{ok, listen} -> spawn(?MODULE, connect, [listen]),
io:format("~p Server started.~n", [erlang:localtime()]);
Error ->
io:format("Error: ~p~n", [Error])
end.
connect(Listen) ->
{ok, Socket} = gen_tcp:accept(Listen),
inet:setopts(Socket, ?TCP_OPTS),
% kick off another process to handle connections concurrently
spawn(fun() -> connect(Listen) end),
recv_loop(Socket),
gen_tcp:close(Socket).
recv_loop(Socket) ->
% reset the socket for flow control
inet:setopts(Socket, [{active, once}]),
receive
% do something with the data
{tcp, Socket, Data} ->
io:format("~p ~p ~p~n", [inet:peername(Socket), erlang:localtime(), Data]),
gen_tcp:send(Socket, "I received: " ++ Data),
recv_loop(Socket);
% exit loop if client disconnects
{tcp_closed, Socket} ->
io:format("~p Client Disconnected.~n", [erlang:localtime()])
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment