some_id
some_id

Reputation: 29886

sending raw binary using tcp in erlang

I have a basic client server in erlang which uses tcp.

How does one send the actual binary data from a file to the client who requested it?

How is the file sent in pieces?

I have this code

{ok, Socket} = gen_tcp:connect({Ip}, 2345, [binary, {packet, 4}]),

Does this {packet, 4} handle the data size that is send both ways?

Also, how does the client receive data and then do something with it? Like save it to a file?

Thanks

Upvotes: 3

Views: 3020

Answers (1)

archaelus
archaelus

Reputation: 7129

Yes - {packet, 4} will cause erlang to require a packet frame of a 4 byte unsigned big endian integer length value on receive, and will emit one before each packet of data sent.

You can send data on the socket by calling gen_tcp:send(Socket, Data). This will do something like:

RawData = iolist_to_binary(Data),
Length = byte_size(RawData),
Packet = <<Length:32/big-unsigned-integer, RawData/binary>>,
send(Socket, Packet).

So provided your file is less than 4Gb, you could send it by doing

{ok, File} = file:read_file(FileName),
gen_tcp:send(Socket, File).

On the receiving end:

File = gen_tcp:recv(Socket, 0).

You'll get the complete file because of the {packet, 4} framing.

Upvotes: 9

Related Questions