質問

Why does this program run successfully when calling start/0 but not when calling run/0? When I start the program by calling run/0, I get {error, closed} from gen/tcp.

-module(echo_server).
-compile(export_all).
run() ->
    spawn(fun() -> start() end).
start() ->
    {ok, Listen} = gen_tcp:listen(12345, [binary,{packet,0},
                                         {reuseaddr,true},
                                         {active, true}]),
spawn(fun() -> par_connect(Listen) end).
par_connect(Listen) ->
    {ok,Socket} = gen_tcp:accept(Listen),       
    spawn(fun() -> par_connect(Listen) end ),
    loop(Socket).
loop(Socket) ->
    receive
        {tcp,Socket,Bin} =Msg ->
            io:format("received ~p~n",[Msg]),
            gen_tcp:send(Socket,Bin),
            loop(Socket);
        Any ->
            io:format("any other received ~p~n",[Any]),
            gen_tcp:close(Socket)
    end.
役に立ちましたか?

解決

when you run echo_server:start(), the shell becomes the owner of the socket that you open. when the start function returns, the socket is still open because the shell is still alive. if you deliberately crash your shell (enter something like 3=2.), the socket will close.

echo_server:run(), on the other hand, starts a new process that owns the socket. when start returns and that new process exits, the socket gets closed.

one solution would be for your start function to stick around (for example, add a receive with no timeout).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top