今日主要是对gen_server之间的通信进行简单练习
-module(my_bank).
-define(SERVER, ?MODULE).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3, test/0, start_link/0, stop/0, new_account/1, withdraw/2, deposit/2, sendMsg/1,start/0]).
start() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
stop() -> gen_server:call(?MODULE, stop).
new_account(Who) -> gen_server:call(?MODULE, {new, Who}).
deposit(Who, Amount) -> gen_server:call(?MODULE, {add, Who, Amount}).
withdraw(Who, Amount) -> gen_server:call(?MODULE, {remove, Who, Amount}).
sendMsg(Who) -> gen_server:call(?MODULE, {send, Who}).
start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
init([]) -> {ok, ets:new(?MODULE, [])}.
handle_call({new, Who}, _From, Tab) ->
Reply = case ets:lookup(Tab, Who) of
[] -> ets:insert(Tab, {Who, 0}), {welcome, Who};
_ -> {Who, you_already_are_a_customer}
end,
{reply, Reply, Tab};
handle_call({add, Who, X}, _From, Tab) ->
Reply = case ets:lookup(Tab, Who) of
[] -> not_a_customer;
[{Who, Balance}] ->
NewBalance = Balance + X,
ets:insert(Tab, {Who, NewBalance}),
{thanks, Who, your_balance_is, NewBalance}
end,
{reply, Reply, Tab};
%%在昨天的基础上增加了send模块将用户的名字和资金数发送给gen_server1
handle_call({send, Who}, _From, Tab) ->
case ets:lookup(Tab, Who) of
[] -> not_a_customer;
[Msg = {Who, _}] ->
gen_server1:send_msg(Msg)
end,
{reply, ok, Tab};
handle_call({remove, Who, X}, _From, Tab) ->
Reply = case ets:lookup(Tab, Who) of
[] -> not_a_customer;
[{Who, Balance}] when X =< Balance ->
NewBalance = Balance - X,
ets:insert(Tab, {Who, NewBalance}),
{thanks, Who, your_balance_is, NewBalance};
[{Who, Balance}] ->
{sorry, Who, you_only_have, Balance, in_the_bank}
end,
{reply, Reply, Tab};
handle_call(stop, _From, Tab) ->
{stop, normal, stopped, Tab}.
handle_cast(_Msg, State) -> {noreply, State}.
handle_info(_Info, State) -> {noreply, State}.
terminate(_Reason, _State) -> ok.
code_change(_OldVsn, State, _Extra) -> {ok, State}.
test() ->
start().
-module(gen_server1).
-export([start_link/0, init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, send_msg/1]).
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
init([]) ->
{ok, []}.
handle_call(_Msg, _From, State) ->
{noreply, State}.
%%核心是该方法,用于接收my_bank中传入的名字与资金并打印
handle_cast({receive_msg, Msg}, State) ->
{Name, Balance} = Msg,
io:format("Received message: ~p, balance: ~p~n", [Name, Balance]),
{noreply, State}.
handle_info(_Msg, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
send_msg(Msg) ->
gen_server:cast(gen_server1, {receive_msg, Msg}).
以下是运行截图