Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
43 lines (34 sloc) 1.26 KB
-module(say_tcp_server).
-behaviour(gen_server).
-export([start_link/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, code_change/3, terminate/2]).
-record(state, {socket}).
start_link(Socket) ->
gen_server:start_link(?MODULE, Socket, []).
init(Socket) ->
gen_server:cast(self(), accept),
{ok, #state{socket=Socket}}.
handle_cast(accept, State = #state{socket=ListenSocket}) ->
{ok, AcceptSocket} = gen_tcp:accept(ListenSocket),
say_tcp_sup:start_socket(),
{noreply, State#state{socket=AcceptSocket}};
handle_cast(_, State) ->
{noreply, State}.
handle_info({tcp, Socket, Msg}, State) ->
[Command|Args] = say_command_parser:from_redis(Msg),
Data = say_command:run(Command, Args),
ParsedData = say_command_parser:to_redis(Data),
send(Socket, ParsedData),
{noreply, State};
handle_info({tcp_closed, _Socket}, State) -> {stop, normal, State};
handle_info({tcp_error, _Socket, _}, State) -> {stop, normal, State};
handle_info(E, State) ->
lager:debug("unexpected: ~p~n", [E]),
{noreply, State}.
handle_call(_E, _From, State) -> {noreply, State}.
terminate(_Reason, _Tab) -> ok.
code_change(_OldVersion, Tab, _Extra) -> {ok, Tab}.
send(Socket, Str) ->
ok = gen_tcp:send(Socket, Str),
ok = inet:setopts(Socket, [{active, once}]),
ok.