[erlang-questions] using a socket to send and receive

Roberto Ostinelli <>
Thu Aug 19 15:22:55 CEST 2010

2010/8/19 Essien Essien <>:
> My approach is still to use {active, once}, thus recieving _all_
> available data. When I process though, I only take the lenght of data
> that I need and leave the Rest in a loop variable. The next time
> around, I prepend the Rest from the previous run to the new coming
> data, then recurse. So, something like this:
> % I'm assuming that the socket is delivering
> % binary not list data.
> sock_loop(Sock, Len, Rest0) ->
>        inet:setopts(Sock, [{active, once}]),
>        receive
>                {http, Sock, Data0} ->
>                        % data received from TCP socket, do something with it
>                        % first prepend pending data in Rest0 before continuing
>                        Data1 = list_to_binary([Rest0, Data0]),
>                        <<Data:Len,Rest1/binary>> = Data1,
>                         % Now you can do what you want with Data
>                          worker_proc ! <<Data:Len>>,
>                           sock_loop(Sock, Len, Rest1);
>                {send, DataToSend} ->
>                        % data received from external processes, send
> it to socket
>                        gen_tpc:send(Sock, DataToSend)
>        end.

hi essien,

first of all thank you for your reply.

unfortunately this is not enough: you are assuming that you can match
<<Data:Len,Rest1/binary>> = Data1, which is not true if Len > what you
have received. therefore, you would need additional checks.

that apart, i don't want to go this way because i find it
overcomplicated in respect to using passive mode.

there really are no other alternatives?

thank you,


More information about the erlang-questions mailing list