Advertisement
Guest User

Untitled

a guest
May 22nd, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.35 KB | None | 0 0
  1. -module(mappingserver).
  2.  
  3. -behaviour(gen_server).
  4. -export([start/0]).
  5. %% gen_server callbacks
  6. -export([init/1, handle_call/3, handle_cast/2, handle_info/2,
  7.          terminate/2, code_change/3]).
  8. -compile(export_all).
  9.  
  10.  
  11. start() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
  12. stop()  -> gen_server:call(?MODULE, stop).
  13.  
  14. lookup_port(Host)     -> gen_server:call(?MODULE, {port, Host}).
  15. lookup_command(Host)  -> gen_server:call(?MODULE, {command, Host}).
  16. refresh()  -> gen_server:call(?MODULE, {refresh}).
  17.  
  18.  
  19. refresh_file() ->
  20.     {ok,List} = file:consult("mapping.dat"),
  21.     dict:from_list([{Host,{Port,Command}} || {Host,Port,Command} <- List]).
  22.  
  23. init([]) ->
  24.     State = refresh_file(),
  25.     timer:apply_interval(60*1000,?MODULE,refresh,[]),
  26.     {ok, State}.
  27.  
  28. handle_call({port,Host}, _From, State) ->
  29.     {Reply,_} = dict:fetch(Host,State),
  30.     {reply, Reply, State};
  31. handle_call({command,Host}, _From, State) ->
  32.     {_,Reply} = dict:fetch(Host,State),
  33.     {reply, Reply, State};
  34. handle_call({refresh}, _From, State) ->
  35.     NewState = refresh_file(),
  36.     {reply, ok, NewState};
  37.  
  38. handle_call(stop, _From, State) ->
  39.     {stop, normal, stopped, State}.
  40.  
  41. handle_cast(_Msg, State) -> {noreply, State}.
  42. handle_info(_Info, State) -> {noreply, State}.
  43. terminate(_Reason, _State) -> ok.
  44. code_change(_OldVsn, State, Extra) -> {ok, State}.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement