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

zabrane Mikael <>
Thu Aug 19 18:48:07 CEST 2010


A lazy one, in the same spirit of Hynek solution:

sock_loop_lazy(Sock, Len) ->
    sock_loop_lazy(Sock, Len, [], 0).

sock_loop_lazy(Sock, Len, BuffList, BuffLen) when Len > BuffLen ->
   inet:setopts(Sock, [{active, once}]),
    receive
        {http, Sock, Data} ->
            sock_loop_lazy(Sock, Len, [Data | BuffList], BuffLen + size(Data));
        {send, DataToSend} ->
            % data received from external processes, send it to socket
            gen_tpc:send(Sock, DataToSend),
            sock_loop_lazy(Sock, Len, BuffList, BuffLen)
    end;

sock_loop_lazy(Sock, Len, BuffList, BuffLen)  ->
    % We have enough data
    <<Data:Len,Rest1/binary>> = list_to_binary(lists:reverse(BuffList)),
    worker_proc ! {data, Data},
    sock_loop_lazy(Sock, Len, Rest1, BuffLen - Len).


/Zab


More information about the erlang-questions mailing list