aboutsummaryrefslogtreecommitdiffstats
path: root/common
diff options
context:
space:
mode:
authorAlexander Sulfrian <alexander@sulfrian.net>2010-10-13 23:15:11 +0200
committerAlexander Sulfrian <alexander@sulfrian.net>2010-10-13 23:15:11 +0200
commit398ee976066c88df5d7cd38086c021faa479614d (patch)
treebfb967b68b0730ce800fbc15544e602913790f19 /common
parenta6784d57c203b61b09b4a6d5d8895a666d89327f (diff)
downloaderlang-398ee976066c88df5d7cd38086c021faa479614d.tar.gz
erlang-398ee976066c88df5d7cd38086c021faa479614d.tar.xz
erlang-398ee976066c88df5d7cd38086c021faa479614d.zip
moved server to common (used from server and client)
Diffstat (limited to 'common')
-rw-r--r--common/server.erl49
1 files changed, 49 insertions, 0 deletions
diff --git a/common/server.erl b/common/server.erl
new file mode 100644
index 0000000..06922cc
--- /dev/null
+++ b/common/server.erl
@@ -0,0 +1,49 @@
+%% Inspired by "Programming Erlang",
+%% published by The Pragmatic Bookshelf.
+%% Copyrights apply to this code.
+%% We make no guarantees that this code is fit for any purpose.
+%% Visit http://www.pragmaticprogrammer.com/titles/jaerlang for more book information.
+
+-module(server).
+-export([start/2, start/3, rpc/2, swap_code/2]).
+
+start(Name, Mod) ->
+ register(Name, spawn(fun() -> loop(Name, Mod, Mod:init()) end)).
+
+start(Name, Mod, State) ->
+ register(Name, spawn(fun() -> loop(Name, Mod, State) end)).
+
+swap_code(Name, Mod) -> rpc(Name, {swap_code, Mod}).
+
+rpc(Name, Request) ->
+ Name ! {self(), Request},
+ receive
+ {Name, crash} -> exit(rpc);
+ {Name, ok, Response} -> Response
+ end.
+
+loop(Name, Mod, OldState) ->
+ receive
+ {From, {swap_code, NewCallbackMod}} ->
+ From ! {Name, ok, ack},
+ loop(Name, NewCallbackMod, 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
+ end.
+
+log_the_error(Name, Request, Why) ->
+ io:format("Server ~p request ~p ~n"
+ "caused exception ~p~n",
+ [Name, Request, Why]).