Receive binary data from a TCP server and save it to a file
How Does a TCP client receive binary data it requests from a TCP server?
If the server sends开发者_开发问答 the requested data (some binary data at a certain position of file) how is this received and saved to a file.
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 a 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>
You use gen_tcp:recv to receive the data. A regular write can then save them to a file.
精彩评论