%% --- %% Excerpted from "Programming Erlang", %% published by The Pragmatic Bookshelf. %% Copyrights apply to this code. It may not be used to create training material, %% courses, books, articles, and the like. Contact us if you are in doubt. %% We make no guarantees that this code is fit for any purpose. %% Visit http://www.pragmaticprogrammer.com/titles/jaerlang for more book information. %%--- -module(name_server). -export([init/0, ns_add/2, ns_whereis/1, handle/2, go/0]). -import(server1, [rpc/2]). %% client routines ns_add(Name, Place) -> rpc(name_server, {add, Name, Place}). ns_whereis(Name) -> rpc(name_server, {whereis, Name}). %% callback routines init() -> dict:new(). handle({add, Name, Place}, Dict) -> {ok, dict:store(Name, Place, Dict)}; handle({whereis, Name}, Dict) -> {dict:find(Name, Dict), Dict}. % test go() -> % unregister(name_server), server1:start(name_server,name_server), ns_add(joe,home), ns_add(bob,work), {ok,home} = ns_whereis(joe), {ok,work} = ns_whereis(bob), error = ns_whereis(alice), ns_add(alice,hawaii), {ok,hawaii} = ns_whereis(alice), ns_add(bob,home), {ok,home} = ns_whereis(bob), ok.