Erlang catch断开客户端

0xA*_*xAX 0 sockets erlang client disconnect

我有用erlang和命令处理程序编写的tcp服务器.如果客户端连接到我的服务器,然后关闭如何捕获网络断开连接?

aru*_*esh 8

我认为你正在使用vanilla gen_tcp来实现你的服务器.在这种情况下,当从客户端关闭套接字时,acceptor进程(传递Socket的进程)将收到{tcp_closed,Socket}消息.

来自erlang gen_tcp文档的示例代码.

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.