[erlang-questions] Why this code not being infinite recursive?

by by@REDACTED
Fri Jun 14 06:56:29 CEST 2019


Hi,

The acceptor is waiting for new TCP connection.
If a new connection arrives, it will spawn a new process waiting for future new connection first, then the current process will handle communication on the connected connection.

Best Regards,
Yao

> 在 2019年6月14日,12:45,I Gusti Ngurah Oka Prinarjaya <okaprinarjaya@REDACTED> 写道:
> 
> Hi,
> 
> I learn gen_tcp from learnyousomeerlangg book. I try to understand flow of code below. 
> And i got confused with acceptor/1 . Because acceptor/1 call itself but have no base case and just execute once. It's not usual. Why? 
> From my understanding it should be an infinity recursive.
> 
> -module(naive_tcp).
> -compile(export_all).
> 
> start_server(Port) ->
>   Pid = spawn_link(
>     fun() ->
>       io:format("Spawned at start_server()~n"),
>       {ok, ListenSocket} = gen_tcp:listen(Port, [binary, {active, false}]),
>       spawn(fun() -> acceptor(ListenSocket) end),
>       timer:sleep(infinity)
>     end
>   ),
>   {ok, Pid}.
> 
> acceptor(ListenSocket) ->
>   io:format("I am acceptor~n"),
>   {ok, AcceptorSocket} = gen_tcp:accept(ListenSocket),
>   spawn(fun() -> acceptor(ListenSocket) end),
>   handle(AcceptorSocket).
> 
> handle(AcceptorSocket) ->
>   inet:setopts(AcceptorSocket, [{active, once}]),
>   receive
>     {tcp, AcceptorSocket, <<"quit", _/binary>>} ->
>       gen_tcp:close(AcceptorSocket);
>     {tcp, AcceptorSocket, Message} ->
>       gen_tcp:send(AcceptorSocket, Message),
>       handle(AcceptorSocket)
>   end.
> 
> Please enlightenment 
> 
> Thank you 
> 
> 
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20190614/9cb84c91/attachment.htm>


More information about the erlang-questions mailing list