刚才又重新 理解Gen_server才明白它的工作原理。
handle_call : 是进程之间的调用.. 需要返回值
gen_server完全写好一套消息框架,只需要实现它的功能函数既可。
-module(test_A). -behaviour(gen_server). %%External exports -export([start_link/0,handleCall/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {}). %% ==================================================================== %% Server functions %% ==================================================================== init([]) -> process_flag(trap_exit, true), {ok, #state{}}. handle_call({first,Data},_From,State)-> io:format("recv call backMSG~p~n",[_From]), {reply,Data,State}; handle_call(_Request,_From,State)-> Reply = ok, io:format("call recv = ~p~n", Reply), {reply,Reply,State}. handle_cast(Msg, State) -> {noreply, State}. handle_info(Info, State) -> {noreply, State}. terminate(Reason, State) -> ok. code_change(OldVsn, State, Extra) -> {ok, State}. %% ==================================================================== %% Server functions %% ==================================================================== start_link()-> gen_server:start_link({local, ?MODULE},?MODULE, [], []). handleCall(PID)-> Name = gen_server:call(PID,{first,"Lee"}), io:format("名字是~p~n",[Name]).
-module(test_B). -behaviour(gen_server). %%External exports -export([start_link/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {}). %% ==================================================================== %% Server functions %% ==================================================================== init([]) -> process_flag(trap_exit, true), {ok, #state{}}. handle_call({first,Data},_From,State)-> io:format("recv From= ~p~n", [_From]), {reply,Data,State}; handle_call(_Request,_From,State)-> Reply = ok, {reply,Reply,State}. handle_cast(Msg, State) -> {noreply, State}. handle_info(Info, State) -> io:format("recv = ~p~n", [Info]), {noreply, State}. terminate(Reason, State) -> ok. code_change(OldVsn, State, Extra) -> {ok, State}. %% ==================================================================== %% Server functions %% ==================================================================== start_link()-> gen_server:start_link({local, ?MODULE},?MODULE, [], []).