Erlang--TCP学习(一)Client篇

  gen_tcp:connect(Host,Port,[Options]),gen_tcp:send(Socket, Request)。用这个两个函数从服务器获取数据
  代码如下:tcp_client.erl
-module(tcp_client).

-export([get_url/0]).

get_url() ->
    get_url("www.baidu.com").

get_url(Host) ->
    {ok, Socket} = gen_tcp:connect(Host, 80, [binary, {packet, 0}]),
    ok = gen_tcp:send(Socket, "GET / HTTP/1.0\r\n\r\n"),
    receive_data(Socket, []).

receive_data(Socket, SoFar) ->
    receive
        {tcp, Socket, Bin} ->
              receive_data(Socket, [Bin|SoFar]);
        {tcp_closed, Socket} ->
              list_to_binary(lists:reverse(SoFar));
          R ->
              io_lib:format("error msg receive ~s",[R])
    end.


编译和运行:
erlc tcp_client.erl
erl
B = tcp_client:get_url(),
io:format("~p~n",[B]).
string:tokens(binary_to_list(B), "\r\n").

你可能感兴趣的:(socket,tcp)