Created
September 27, 2015 21:33
-
-
Save dc0d/0305f6f423c2ebec6399 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(server2). | |
-export([start/2, rpc/2]). | |
start(Name, Mod) -> | |
register(Name, spawn(fun() -> loop(Name,Mod,Mod:init()) end)). | |
rpc(Name, Request) -> | |
Name ! {self(), Request}, | |
receive | |
{Name, crash} -> exit(rpc); | |
{Name, ok, Response} -> Response | |
end. | |
loop(Name, Mod, OldState) -> | |
receive | |
{From, Request} -> | |
try Mod:handle(Request, OldState) of | |
{Response, NewState} -> | |
From ! {Name, ok, Response}, | |
loop(Name, Mod, NewState) | |
catch | |
_:Why -> | |
log_the_error(Name, Request, Why), | |
%% send a message to cause the client to crash | |
From ! {Name, crash}, | |
%% loop with the *original* state | |
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]). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment