Search code examples
erlanggen-tcp

What's the binary that gen_tcp:recv received?


loop(Socket) ->
    case gen_tcp:recv(Socket, 0) of
        {ok, Bin} ->
            io:format("Bin=~p~n", [Bin]),
            loop(Socket);
        {error, Reason} ->
            io:format("Reason=~p~n", [Reason])
    end.

{env, [
    {tcp_listen_options, [binary, {active, false}, {packet, 0}, {reuseaddr, true}, {backlog, 256}]},
    {port, 5678}
]}

Whether I set packet to 0 or 1, 2, 4, always get following:

gen_tcp:send(S1,term_to_binary("1")). output <<131,107,0,1,49>>
gen_tcp:send(S1,term_to_binary(a)). output <<131,100,0,1,97>>
gen_tcp:send(S1,term_to_binary("abcd")). output <<131,107,0,4,97,98,99,100>>
gen_tcp:send(S1,term_to_binary(1)). output <<131,97,1>>

My questions are:
1. What is <<131,107>>?
2. Send 1 instead of "1" and get binary without packet length like '131,107,0,1', why?


Solution

  • When you use term_to_binary you convert your erlang value to external term format. 131 is a header for that format. 107 means "next bytes are string" You can read it here: http://www.erlang.org/doc/apps/erts/erl_ext_dist.html

    I believe you dont need term_to_binary here. You might use

    gen_tcp:send(S1,<< "abcd" >>)
    

    instead