Skip to content

Instantly share code, notes, and snippets.

@clickclickmoon
Created November 30, 2009 20:51
Show Gist options
  • Save clickclickmoon/245731 to your computer and use it in GitHub Desktop.
Save clickclickmoon/245731 to your computer and use it in GitHub Desktop.
%% connection/1
%%==============================================================================
%% There are two common idioms I've found for this. (A) This function spawns a
%% handler loop and then recuses on itself. (B) This function spawns another of
%% itself and calls the handler loop. (A) makes more sense for the socket close
%% handling to be sure that it's getting done.
connection(Listen, ClientListPid) ->
% Accept a connection and set it up for incoming connections
{ok, Socket} = gen_tcp:accept(Listen),
inet:setopts(Socket, ?TCP_OPTS),
% Start up another handler.
spawn(fun() -> connection(Listen) end),
% Inform the client_list of a new client and start the handler loop
Client = #client{port_pid = self()},
ClientListPid ! {new, Client},
receive_loop(Socket),
gen_tcp:close(Socket).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment