erlang의 유니버설 서버 길 (1)

1971 단어 erlang서버
드디어 otp 부분을 공략하러 왔습니다.을 참고하여 개인 필기.
서버 1: 기본 서버
-module(server1).

%%% =================================================================
%%% API functions
%%% =================================================================
-export([start/2,
		 rpc/2]).



%%% =================================================================
%%% Internal functions
%%% =================================================================


start(Name,Mod) ->
	register(Name,spawn(fun()->loop(Name,Mod,Mod:init())end)).
rpc(Name,Request) ->
	Name ! {self(),Request},
	receive
		{Name,Response} ->Response
	end.
loop(Name,Mod,State)->
	receive
		{From,Request} ->
			{Response,State1} = Mod:handle(Request,State),
			From ! {Name,Response},
			loop(Name,Mod,State1)
	end.

이름 서버 콜백 모듈인 server1에 콜백 함수 모듈을 작성합니다.
-module(name_server).

%%% =================================================================
%%% API functions
%%% =================================================================
-export([init/0,add/2,find/1,handle/2]).
-import(server1,[rpc/2]).



%%% =================================================================
%%%  
%%% =================================================================


add(Name,Place) ->rpc(name_server,{add,Name,Place}).
find(Name)      ->rpc(name_server,{find,Name}).

%% 
init() ->dict:new().
handle({add,Name,Place},Dict)->{ok,dict:store(Name, Place, Dict)};
handle({find,Name},Dict) ->{dict:find(Name, Dict),Dict}.

테스트:
([email protected])2> make:all().
Recompile: src/server1
Recompile: src/name_server
up_to_date
([email protected])3> server1:start(name_server,name_server).
true
([email protected])4> name_server:add(joe,"at home").
ok
([email protected])5> name_server:find(joe).
{ok,"at home"}
([email protected])6> 

주의:name_서버 모듈에서 rpc를 직접 호출하는 것은 위의import가 있기 때문입니다.

좋은 웹페이지 즐겨찾기