Advertisement
Guest User

Simple TCP

a guest
May 9th, 2011
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.84 KB | None | 0 0
  1. -module(interface_server2).
  2. -behaviour(gen_server).
  3. -compile(export_all).
  4. -record(interface_state, {port, lsock, buffer}).
  5.  
  6. process_data([13,10], State) ->
  7.     exec_call(State),
  8.     New_state = State#interface_state{buffer = []},
  9.     New_state;
  10.  
  11. process_data(RawData, State) ->
  12.     Buffer = State#interface_state.buffer,
  13.     New_state = State#interface_state{buffer = Buffer ++ RawData},
  14.     New_state.
  15.  
  16.  
  17. args_to_terms(RawArgs) ->
  18.     {ok, Toks, _Line} = erl_scan:string("[" ++ RawArgs ++ "]. ", 1),
  19.     {ok, Args} = erl_parse:parse_term(Toks),
  20.     Args.
  21.  
  22. exec_call(State) ->
  23.     Socket = State#interface_state.lsock,
  24.     Buffer = State#interface_state.buffer,
  25.     {match, [XMod, XFun, XArgs]} = re:run(Buffer, "^([^\s]+):([^\s]+)\\(\s*(.*)\s*\\)$", [{capture, [1, 2, 3], list}]),
  26.     Mod = list_to_atom(XMod),
  27.     Fun = list_to_atom(XFun),
  28.     Args = args_to_terms(XArgs),
  29.     io:format("~p:~p~w~n", [Mod, Fun, Args]),
  30.     Result = apply(Mod, Fun, Args),
  31.     gen_tcp:send(Socket, io_lib:fwrite("~p~n", [Result])),
  32.     io:format("~w~n", [Result]).
  33.  
  34.  
  35. start_link(Port) -> gen_server:start_link({local, ?MODULE}, ?MODULE, [Port], []).
  36.  
  37. init([Port]) ->
  38.     {ok, LSock} = gen_tcp:listen(Port, [{active, true}]),
  39.     {ok, #interface_state{port = Port, lsock = LSock, buffer=[]}, 0}.
  40.  
  41. handle_info({tcp, _Socket, RawData}, State) ->
  42.     New_state = process_data(RawData, State),
  43.     {noreply, New_state};
  44.    
  45. handle_info(timeout, #interface_state{lsock = LSock} = State) ->
  46.     {ok, _Sock} = gen_tcp:accept(LSock),
  47.     {noreply, State}.
  48.  
  49. handle_cast(stop, State) -> {stop, normal, State}.
  50.  
  51. %handle_call(_Request, _From, State) -> {reply, Reply, State}.
  52. %handle_cast(_Msg, State) -> {noreply, State}.
  53. %handle_info(_Info, State) -> {noreply, State}.
  54. terminate(_Reason, _State) -> ok.
  55. code_change(_OldVsn, State, _Extra) -> {ok, State}.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement