Strange 'receive' from socket.

Alex Arnon <>
Mon May 16 12:41:02 CEST 2005


Hi All,

I have started playing around with sockets, and have encountered the
following problem:
- I open a read socket (e.g. to 'chargen' port (19) for testing).
- Perform a receive on either {tcp, Socket, Data} or Other (as sink).
- Even when I _always_ get a message {tcp, _, _}, sometimes the
'receive' acts on the sink branch.

So, from the program below I receive either:

----------------------------------------------

32> client_test:go("10.10.10.8", 19, 3).
Opened #Port<0.145>
#Port<0.145> => <<32,33,34,35,36,...,10>>
#Port<0.145> => <<33,34,35,36,37,...,105,106,107>>
#Port<0.145> => <<108,109,110,111,...,122,123,13,10>>
#Port<0.145> [closing]
ok
33>

-----------------------------------------------

or

-----------------------------------------------

31> client_test:go("10.10.10.8", 19, 3).
Opened #Port<0.144>
#Port<0.144> [unknown] :
{tcp,#Port<0.143>,<<53,54,55,56,...,123,124,125,126,32>>}
ok

------------------------------------------------


I have witnessed this behaviour on both Win2K and OpenBSD.

The program:

------------------------------------------------

-module(client_test).
-export([go/3]).

%%
%% 
%%

go (Server, Port, Iterations)
  when list(Server), integer(Port), integer(Iterations), Iterations > 0 ->
    case gen_tcp:connect(Server, Port, [binary, {packet, 0}]) of
        {ok, Socket} ->
            io:format("Opened ~w~n", [Socket]),
            do_read(Socket, Iterations),
            gen_tcp:shutdown(Socket, read_write),
            gen_tcp:close(Socket),
            ok;
        _ ->
            error
    end.


do_read (Socket, Iterations) when Iterations > 0 ->
    receive
        {tcp, Socket, Data} ->
            io:format("~w => ~w~n", [Socket, Data]),
            do_read(Socket, Iterations-1);
        Other ->
            io:format("~w [unknown] : ~w~n", [Socket, Other]),
            error
    after
        5000 ->
            io:format("~w [timeout]~n", [Socket]),
            error
    end;

do_read (Socket, _Iterations) when _Iterations == 0 ->
    io:format("~w [closing]~n", [Socket]),
    ok.

----------------------------------------------

P.S. Apologies for style :)



More information about the erlang-questions mailing list