Search code examples
socketserlangclientdisconnect

Erlang catch disconnect client


I have tcp server written in erlang and command handler. If client connect to my server, and then closing how can i catch network disconnect?


Solution

  • I presume u are using vanilla gen_tcp to implement your server. In which case, acceptor process (the process you pass the Socket to) will receive a {tcp_closed, Socket} message when the socket is closed from the client end.

    sample code from the erlang gen_tcp documentation.

    start(LPort) ->
        case gen_tcp:listen(LPort,[{active, false},{packet,2}]) of
            {ok, ListenSock} ->
                spawn(fun() -> server(LS) end);
            {error,Reason} ->
                {error,Reason}
        end.
    
    server(LS) ->
        case gen_tcp:accept(LS) of
            {ok,S} ->
                loop(S),
                server(LS);
            Other ->
                io:format("accept returned ~w - goodbye!~n",[Other]),
                ok
        end.
    
    loop(S) ->
        inet:setopts(S,[{active,once}]),
        receive
            {tcp,S,Data} ->
                Answer = do_something_with(Data), 
                gen_tcp:send(S,Answer),
                loop(S);
            {tcp_closed,S} ->
                io:format("Socket ~w closed [~w]~n",[S,self()]),
                ok
        end.