TCP/IP Stream and recv?

Chris Campbell <>
Wed Feb 8 19:36:16 CET 2006


Hi,

This may be a misunderstanding of tcp but here goes.  The following
client sends two messages to a client one after the other, then waits
5 seconds and exits.  The server waits for 1 second after accepting a
connection, then does 1 call to recv.  It only retrieves the first
message.  Is this Erlang specific or TCP behaviour?  My understanding
of tcp is that it's a stream and recv may return both messages
(ignoring fragmentation for the moment).

I have only used tcp with single requests like HTTP so far. I'm now
toying with something that will send messages back and forth hence why
it's important to know if recv will pull a single message or it just
pulls everything to make account for this in the protocol parser.

Cheers,
Chris


Erlang (BEAM) emulator version 5.4.6 [source] [threads:0]

Eshell V5.4.6  (abort with ^G)
1> c(client).
{ok,client}
2> client:send_server(55806, 'localhost', "GIVE ME LOVE", "TOO LATE").
ok


Erlang (BEAM) emulator version 5.4.6 [source] [threads:0]

Eshell V5.4.6  (abort with ^G)
1> c(srv).
{ok,srv}
2> srv:server(55806).
GIVE ME LOVE
ok


-module(client).
-export([send_server/4]).

send_server(Port, Host, Msg1, Msg2) ->
    {ok, Socket} = gen_tcp:connect(Host, Port,
                                   [binary, {packet, 4}]),
    ok = gen_tcp:send(Socket, Msg1),
    ok = gen_tcp:send(Socket, Msg2),
    delay(4000),
    ok = gen_tcp:close(Socket).

delay(X) ->
    receive
        ok -> ok
    after
        X ->  ok
    end.

--

-module(srv).
-export([server/1]).

server(Port) ->
    {ok, LSock} = gen_tcp:listen(Port, [binary, {packet, 4},
                                        {active, false}]),
    {ok, Sock} = gen_tcp:accept(LSock),
    delay(1000),
    {ok, Bin} = do_recv(Sock),
    ok = gen_tcp:close(Sock),
    ok = gen_tcp:close(LSock),
    io:format("~s~n", [binary_to_list(Bin)]),
    ok.

do_recv(Sock) ->
    gen_tcp:recv(Sock, 0).

delay(X) ->
    receive
        ok -> ok
    after
        X -> ok
    end.

--



More information about the erlang-questions mailing list