0

I'm trying to implement a client server program. Server sets up a listening socket with the following code:

gen_tcp:listen(Port, [binary, {active, true}])

The problem is that when the client sends a large message(list of tuples) to the server, server receives several messages instead. It seems that TCP is splitting the long message into several messages.

How can we handle to get the whole long message at once?

Elik
  • 477
  • 3
  • 6
  • 11
  • 2
    TCP has no notion of messages. You need a higher-level protocol like ØMQ, HTTP or `{ packet, 4 }`. –  Feb 26 '14 at 17:26

1 Answers1

0

i don't think the tcp package is splitted, i test it using the following program.

client.erl

-module(client).
-compile(export_all).

send(Message) ->
    {ok, Socket} = gen_tcp:connect("localhost", 1234, [binary, {packet, 4}]),
    ok = gen_tcp:send(Socket, list_to_binary(Message)),
    gen_tcp:close(Socket).


main() ->
    Message = ["atom" ++ integer_to_list(X) || X <- lists:seq(1, 1000)],
    send(Message).

server.erl

-module(server).
-compile(export_all).

start()->
    {ok, ListenSocket} = gen_tcp:listen(1234, [binary, {packet, 4}, 
                     {active, true}, {reuseaddr, true}]),
    spawn(fun() -> per_connect(ListenSocket) end).

per_connect(ListenSocket) ->
    {ok, Socket} = gen_tcp:accept(ListenSocket),
    spawn(fun() -> per_connect(ListenSocket) end),
    loop(Socket).

loop(Socket) ->
    receive
        {tcp, Socket, Data} ->
            io:format("~p~n", [binary_to_list(Data)]),
            loop(Socket);
        {tcp_closed, Socket} ->
            io:format("closed~n"),
            gen_tcp:close(Socket)
    end.

you can first run server:start()., then run client:main(), you can see the result.

BlackMamba
  • 10,054
  • 7
  • 44
  • 67