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

I Gusti Ngurah Oka Prinarjaya okaprinarjaya@REDACTED
Fri Jun 14 06:45:17 CEST 2019


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20190614/35a6934a/attachment.htm>


More information about the erlang-questions mailing list