[erlang-questions] using a socket to send and receive
Hynek Vychodil
hynek@REDACTED
Thu Aug 19 17:26:01 CEST 2010
sock_loop(Sock, Len, Rest0) when size(Rest0) >= Len ->
% We have enough data
<<Data:Len,Rest1/binary>> = Rest0,
worker_proc ! {data, Data},
sock_loop(Sock, Len, Rest1);
sock_loop(Sock, Len, Rest) ->
inet:setopts(Sock, [{active, once}]),
receive
{http, Sock, Data} ->
sock_loop(Sock, Len, <<Rest/binary, Data/binary>>)
{send, DataToSend} ->
% data received from external processes, send
it to socket
gen_tpc:send(Sock, DataToSend)
sock_loop(Sock, Len, Rest)
end.
It is still too complicated?
On Thu, Aug 19, 2010 at 3:22 PM, Roberto Ostinelli <roberto@REDACTED> wrote:
> 2010/8/19 Essien Essien <essiene@REDACTED>:
>>
>> 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,
>
> r.
>
> ________________________________________________________________
> erlang-questions (at) erlang.org mailing list.
> See http://www.erlang.org/faq.html
> To unsubscribe; mailto:erlang-questions-unsubscribe@REDACTED
>
>
--
--Hynek (Pichi) Vychodil
Analyze your data in minutes. Share your insights instantly. Thrill
your boss. Be a data hero!
Try GoodData now for free: www.gooddata.com
More information about the erlang-questions
mailing list