Receive binary data from a TCP server and save it to a file

How does a TCP client receive the binary data it requests from a TCP server?

If the server sends the requested data (some binary data at a specific position in the file), how it is received and stored in the file.

+3
source share
2 answers

Here is an example of connecting to a remote server, receiving data and writing it to a file:

-module(recv).

-export([example/1]).

recv_data(IoDevice, Sock) ->
  case gen_tcp:recv(Sock, 0) of
    {ok, B} -> 
      ok = file:write(IoDevice, B),
      recv_data(IoDevice, Sock);
    {error, Reason} ->
      error_logger:info_msg("Done receiving data: ~p~n", [Reason]),
      file:close(IoDevice),
      gen_tcp:close(Sock)
  end.

example(FileName) ->
  {ok, IoDevice} = file:open(FileName, [write, binary]),
  {ok, Sock} = gen_tcp:connect("www.google.com", 80, [binary, {packet, raw}, {active, false}]),
  ok = gen_tcp:send(Sock, "GET / HTTP/1.0\r\n\r\n"),
  recv_data(IoDevice, Sock).

This will connect to Google and write the response to the file:

Erlang R14A (erts-5.8) [source] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.8  (abort with ^G)
1> c(recv).
{ok,recv}
2> recv:example("/tmp/test.bin").

=INFO REPORT==== 4-Nov-2010::08:52:59 ===
Done receiving data: closed
ok
3> 
+3
source

You use gen_tcp: recv to get the data. Regular write can then save them to a file.

+5
source

Source: https://habr.com/ru/post/1772749/


All Articles