[erlang-questions] Non-blocking for gen_tcp:accept?

Sölvi Páll Ásgeirsson solvip@REDACTED
Fri Aug 25 11:09:41 CEST 2017


A simple workaround is to accept in an out of band process and send
the socket over to the process wanting non-blocking semantics.
Something like the following:

case gen_tcp:listen(...) of
{ok, Listener} ->
   Parent = self(),
   Acceptor = fun() ->
      {ok, ClientSock} = gen_tcp:accept(Listener),,
      ok = gen_tcp:controlling_process(ClientSock, Parent),
      Parent ! {self(), tcp_accepted, ClientSock}
      end,
   Pid = spawn_link(Acceptor),
...

Cheers
Sölvi

On Fri, Aug 25, 2017 at 6:48 AM, Vance Shipley <vances@REDACTED> wrote:
> On Fri, Aug 25, 2017 at 7:36 AM, Zhongzheng Liu
> <liuzhongzheng2012@REDACTED> wrote:
>> Socket can be set to {active, true} to receive data by message instead
>> of using gen_tcp:recv.
>>
>> But there is no {active_accept, true} option to make accept
>> non-blocking. We have to use the blocking function  gen_tcp:accept,
>> why?
>>
>> Is it a good idea to deliver a message like {tcp, accept, Socket} to
>> the accepting process when a connection is coming?
>
> I certainly think so. I use an undocumented method described here:
> http://www2.erlangcentral.org/wiki/?title=Building_a_Non-blocking_TCP_server_using_OTP_principles#Listener_Process
>
> Of course as it's undocumented you never know when a new version of
> OTP will break it which did in fact happen in a recent release. The
> fix is trivial if you compare the new version to the old.
>
> How about making non-blocking supported folks?
>
> --
>      -Vance
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list