All pastes #243650 Raw Edit

Anonymous

public text v1 · immutable
·published 2006-11-08 19:25 UTC
rendered paste body
-module(tcp_listener).

%%--------------------------------------------------------------------
%% External exports
-export([start_link/1]).

%% Internal exports
-export([init/1,init/0]).


%% Even though this is not a gen_server
%% it is started and returns in the same fashion
start_link(Port) ->
    {ok, proc_lib:spawn_link(?MODULE, init, [Port])}.

%%--------------------------------------------------------------------

%% Open a socket on Port. If it fails, try again.
%% Then go into accept-loop (see loop/1)
init () ->
    init(17000).
init(Port) ->
    Response = gen_tcp:listen(Port, [list, {packet, 0},
                                     {active, false}]),
    case Response of
        {ok, LSock} ->
            io:format("tcp_listener: socket opened on port ~p~n", [Port]),
            loop(LSock);
        {error, Reason} ->
            io:format("tcp_listener: listen failed with reason ~p~n", [Reason]),
            io:format("tcp_listener: Will try again in 5 seconds...~n"),
            timer:sleep(5000),
            init(Port);
        _ ->
            io:format("tcp_listener: listen returned wierd.~n")
    end.


%% Accepts incoming connections, and creates a new session when a socket
%% is established. Nothing is read from the socket.
loop(LSock) ->
%%    io:format("in tcp_listener loop~n"),
    case gen_tcp:accept(LSock) of
        {ok, Sock} ->
            %%{ok, _Pid} = ho_controller:create_session(Sock),
            %%{ok, _Pid} = io:format("tcp_listener: connection received on port ~p~n", [Port]),
            %%{ok, _Pid} = io:format("tcp_listener: connection received on port ~p ",Sock),
            io:format("tcp_listener: connection received on port ~n"),
            io:fwrite("tcp_listener: running in pid ~p\n", [self()]),
            {ok,[Bin]} = gen_tcp:do_recv(Sock,[]),
            io:format("tcp_listner: read ~p ~n",Bin),
            gen_tcp:send(Sock,"999999"),
            loop(LSock);
        {error, closed} ->
            io:format("tcp_listener: going down!~n");
        X ->
            io:format("tcp_listener: got unhandled message ~p~n", [X])
    end.