-module(lrpc). %-compile(export_all). -export([start_server/0, server_main/0, sum/3, max/3]). %-define(DEBUG, true). -ifdef(DEBUG). -define(RETURN(ClientPid, X), io:fwrite("To: ~w, Returns:~w\n", [ClientPid, X])). -else. -define(RETURN(ClientPid, X), ClientPid!X). -endif. start_server() -> spawn(?MODULE, server_main, []). server_main() -> receive {call, ClientPid, FunctionId, Args} -> % 呼び出しリクエスト case exec(FunctionId, Args) of {error, Reason} -> ?RETURN(ClientPid, {return, error, Reason}); {ok, Value} -> ?RETURN(ClientPid, {return, ok, Value}) end; stop -> % プロセス終了命令 io:fwrite("~w: bye bye.\n", [self()]), exit(ok); _Other -> io:fwrite("Oops!\n") end, server_main(). exec(sum, Args) -> {ok, lists:sum(Args)}; exec(max, Args) -> {ok, lists:max(Args)}; exec(_, _) -> {error, "unknown function."}. %%%% クライアント側 call(ServerPid, FunctionId, Args) -> ServerPid! {call, self(), FunctionId, Args}, receive {return, ok, Value} -> {ok, Value}; {return, error, Reason} -> {error, Reason} after 2*1000 -> {error, "timeout."} end. sum(ServerPid, N, M) -> call(ServerPid, sum, [N, M]). max(ServerPid, N, M) -> call(ServerPid, max, [N, M]).