erlang gen_server 测试

gen_server 的实现简单而高效,joe 的书里边写了原理多些(gen_server 少些),现在想单独来测一下这个功能,在两台机器上边


%kitty.erl 文件

-module(kitty).

-behaviour(gen_server).

-export([start_link/0, order_cat/4, return_cat/2, close_shop/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
         terminate/2, code_change/3]).

-record(cat, {name, color=green, description}).

%%% Client API
start_link() ->
    gen_server:start_link(?MODULE, [], []).

%% Synchronous call
order_cat(Pid, Name, Color, Description) ->
   gen_server:call(Pid, {order, Name, Color, Description}).

%% This call is asynchronous
return_cat(Pid, Cat = #cat{}) ->
    gen_server:cast(Pid, {return, Cat}).

%% Synchronous call
close_shop(Pid) ->
    gen_server:call(Pid, terminate).

%%% Server functions
init([]) -> {ok, []}. %% no treatment of info here!

handle_call({order, Name, Color, Description}, _From, Cats) ->
    if Cats =:= [] ->
        {reply, make_cat(Name, Color, Description), Cats};
       Cats =/= [] ->
        {reply, hd(Cats), tl(Cats)}
    end;
handle_call(terminate, _From, Cats) ->
    {stop, normal, ok, Cats}.

handle_cast({return, Cat = #cat{}}, Cats) ->
    {noreply, [Cat|Cats]}.

handle_info(Msg, Cats) ->
    io:format("Unexpected message: ~p~n",[Msg]),
    {noreply, Cats}.

terminate(normal, Cats) ->
    [io:format("~p was set free.~n",[C#cat.name]) || C <- Cats],
    ok.

code_change(_OldVsn, State, _Extra) ->
    %% No change planned. The function is there for the behaviour,
    %% but will not be used. Only a version on the next
    {ok, State}.

%%% Private functions
make_cat(Name, Col, Desc) ->
    #cat{name=Name, color=Col, description=Desc}.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

1. 远程启动:  erl -name [email protected] -setcookie abc  %启动后就可以用真实ip来访问了


%这里都是本地的访问

2. 本地启动: erl -name [email protected] -setcookie abc

3.net_adm:ping([email protected]).

pong

4. nodes().
['[email protected]']

5. {ok,Pid}=rpc:call('[email protected]',kitty,start_link,[]).
{ok,<7275.63.0>}

6.rd(cat, {name, color=green, description}).     
cat

7. rpc:call('[email protected]',kitty,order_cat,[Pid,"c",black,"1"]).
#cat{name = "c",color = black,description = "1"}

注意这里的参数就可以了,返回正常。

成功了。

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

你可能感兴趣的:(erlang)