aboutsummaryrefslogtreecommitdiffstats
path: root/common/server.erl
diff options
context:
space:
mode:
Diffstat (limited to 'common/server.erl')
-rw-r--r--common/server.erl64
1 files changed, 44 insertions, 20 deletions
diff --git a/common/server.erl b/common/server.erl
index 06922cc..bb64997 100644
--- a/common/server.erl
+++ b/common/server.erl
@@ -5,7 +5,7 @@
%% Visit http://www.pragmaticprogrammer.com/titles/jaerlang for more book information.
-module(server).
--export([start/2, start/3, rpc/2, swap_code/2]).
+-export([start/2, start/3, start_on_node/3, rpc/2, send/2, registration/2]).
start(Name, Mod) ->
register(Name, spawn(fun() -> loop(Name, Mod, Mod:init()) end)).
@@ -13,34 +13,58 @@ start(Name, Mod) ->
start(Name, Mod, State) ->
register(Name, spawn(fun() -> loop(Name, Mod, State) end)).
-swap_code(Name, Mod) -> rpc(Name, {swap_code, Mod}).
+start_on_node(Node, Mod, State) ->
+ Ref = make_ref(),
+ Pid = spawn(Node, fun() -> loop(Ref, Mod, State) end),
+ {Pid, Ref}.
-rpc(Name, Request) ->
- Name ! {self(), Request},
+send({Client, _}, Data) ->
+ send(Client, Data);
+send(Client, Data) ->
+ Client ! Data.
+
+wait_response({_, Name}) ->
+ wait_response(Name);
+wait_response(Name) ->
receive
{Name, crash} -> exit(rpc);
{Name, ok, Response} -> Response
end.
+rpc(Client, Request) ->
+ send(Client, {self(), Request}),
+ wait_response(Client).
+
+registration(Client, NewName) ->
+ send(Client, {register, NewName}).
+
loop(Name, Mod, OldState) ->
receive
- {From, {swap_code, NewCallbackMod}} ->
- From ! {Name, ok, ack},
- loop(Name, NewCallbackMod, OldState);
+ {register, NewName} ->
+ register(NewName, self()),
+ loop(NewName, Mod, OldState);
+
{From, Request} ->
- {Response, NewState} = Mod:handle(From, Request, OldState),
- From ! {Name, ok, Response},
- loop(Name, Mod, NewState)
- %% try Mod:handle(From, Request, OldState) of
- %% {Response, NewState} ->
- %% From ! {Name, ok, Response},
- %% loop(Name, Mod, NewState)
- %% catch
- %% _: Why ->
- %% log_the_error(Name, Request, Why),
- %% From ! {Name, crash},
- %% loop(Name, Mod, OldState)
- %% end
+ try Mod:handle(Request, OldState) of
+ {Response, NewState} ->
+ From ! {Name, ok, Response},
+ loop(Name, Mod, NewState)
+ catch
+ _: Why ->
+ log_the_error(Name, Request, Why),
+ From ! {Name, crash},
+ loop(Name, Mod, OldState)
+ end;
+
+ {'EXIT', From, Why} ->
+ try Mod:handle({'EXIT', From, Why}, OldState) of
+ NewState ->
+ loop(Name, Mod, NewState)
+ catch
+ _: Why ->
+ log_the_error(From, 'EXIT', Why),
+ loop(Name, Mod, OldState)
+ end
end.
log_the_error(Name, Request, Why) ->