[erlang-questions] Erlang get_tcp:recv data length

Alain O'Dea <>
Sat Feb 26 02:58:12 CET 2011


Hi J-Ph,

I am doing well now.  The back problem was temporary thankfully :)

I thought a lot more about this and realised that searchin/2 is totally
unnecessary since binary:match/2 and binary:part/2 can do the heavy lifting
for you:

loop(Socket,BinAcc,Delimiters)->
    inet:setotps(Socket,[{active,once}]),
    receive
        {tcp,Socket,Bin} ->
            Rest = parse(<<BinAcc/binary,Bin/binary>>,Delimiters),
            loop(Socket,Rest);
        {tcp_closed,Socket} ->
            ...
    end.

parse(BinAcc,Delimiters) ->
    case binary:match(BinAcc,Delimiters) of
        {Pos,Len} ->
            <<Message:Pos/binary,Delimiter:Len/binary,Rest/binary>> =
BinAcc,
            process(Message),
            parse(Rest,Delimiters);
        nomatch ->
            BinAcc
    end.

process(_Message) ->
    % spawn process to handle Message
    ok.

Run the following in an EShell to get a feel for binary:match/2 and
binary:part/2:

BinAcc = <<"Hello\nWorld\r\n">>.
Delimiters = [<<"\n">>, <<"\r\n">>, <<"\r">>].
{Pos, Len} binary:match(BinAcc, Delimiters).
<<Message:Pos/binary,Delimiter:Len/binary,Rest/binary>>.
Message.
Delimiter.
Rest.

Cheers,
Alain


On Fri, Feb 25, 2011 at 7:00 PM, info <> wrote:

>  Hello Alain,
>
> Excepted that "searchin" shall extract all valid messages and NOT the first
> valid message !
> Therefore process(Message) becomes process(AllValidMessages).
>
> The objective must be to empty BinAcc...
>
> Do you agree this:
>
>  - The solution will be:
> - independant of the type of delimiter;
> - independant of the size of a message;
> - independant of the number of messages.
> - No need to detect the end of a packet of messages.
> - Standard recbuf can be used.
>
> P.S: are you fine now ? and your back ?
>
>  *J-Ph. Constantin*
> ITS3 Genève
> www.its3.ch
>


More information about the erlang-questions mailing list