[erlang-questions] Setting socket options on listen / accept

Roger Lipscombe roger@REDACTED
Tue Feb 6 12:51:44 CET 2018


It's worth pointing out that certain 'raw' options only apply to the
listening socket, and are not consistently inherited by (or
transferred to) the accepting/connected socket. For example, on Linux,
TCP keep-alive settings can be applied to the listening socket, and
they'll be copied to the connected socket. On macOS, this (a) doesn't
work, and (b) does other weird, unexpected things.

Note also that you probably *don't* want to set {active, true} in
listen/2 in a real application, because you're probably going to hand
the socket off to another process (using
gen_tcp:controlling_process/2), and this'll cause you to miss the
occasional message during that window.

And, frankly, if you're building your own socket acceptor pool,
*don't*. Just use ranch (https://github.com/ninenines/ranch).

On 6 February 2018 at 05:55, Tianxiang Xiong <tianxiang.xiong@REDACTED> wrote:
> In Joe's Programming Erlang 2nd E, Chpt. 17, pg. 274, he says:
>
>> After we have accepted a connection, it’s a good idea to explicitly set
>> the required socket options, like this:
>
>
> {ok, Socket} = gen_tcp:accept(Listen),
> inet:setopts(Socket, [{packet,4},binary,{nodelay,true},{active, true}]),
> loop(Socket)
>
> Until then the book's been doing:
>
> {ok, Listen} = gen_tcp:listen(2345, [binary, {packet, 4}, {reuseaddr, true},
> {active, true}])
> {ok, Socket} = gen_tcp:accept(Listen),
> ...
> loop(Socket)
>
> Is there a reason we need to set the options after accept? Is it necessary
> to set options on listen and accept?
>
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list