从TCP服务器接收二进制数据并将其保存到文件中

时间:2010-11-02 22:36:50

标签: erlang

TCP客户端如何接收它从TCP服务器请求的二进制数据?

如果服务器发送请求的数据(文件某个位置的某些二进制数据),如何接收并保存到文件中。

2 个答案:

答案 0 :(得分:5)

您使用gen_tcp:recv来接收数据。然后,常规write可以将它们保存到文件中。

答案 1 :(得分:4)

以下是连接远程服务器,接收数据并将其写入文件的示例:

-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).

这将连接到谷歌并将回复写入文件:

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>