OTP/TCP server recommendation

tty <>
Wed Aug 10 19:48:35 CEST 2005


Hello,

I am writing an OTP application which requires starting a TCP based server for incoming requests. I want this TCP server to be under a supervisor (for restarts etc).
What is the 'best practice' for this scenario ?

At this moment I have a 'portal' module which looks something like this :

    ===============================================

start_link() ->
    gen_server:start_link({local, ?MODULE}, 
                          ?MODULE, [], []),
    gen_server:cast(?MODULE, server).

init(_Args) ->
    {ok, #state{}}.

handle_cast(server, _State) ->
    server(),
    {noreply, #state{server = ?SERVER, 
                     port = ?PORT}}.

server() ->
    {ok, LSock} = 
         gen_tcp:listen(5600, [binary, {packet, 0}]),
    server(LSock).

server(Socket) ->
    {ok, Sock} = gen_tcp:accept(Socket),
    receive
	{tcp, Sock, Data} ->
	    % do stuff with Data
    end,
    gen_tcp:send(Sock, 
           list_to_binary("all is well\n")),
    gen_tcp:close(Sock),
    server(Socket).

    ===============================================

Although the above works I find it somewhat ugly.

Thanks in advance.

Tee 



More information about the erlang-questions mailing list