Protocol halfway ported

This commit is contained in:
Jonatan Pålsson 2011-02-14 17:18:24 +01:00
parent 6aad821279
commit 973f2fcf98
4 changed files with 66 additions and 56 deletions

View file

@ -2,38 +2,48 @@
-export([parse/1]).
parse(Data) ->
Message =string:tokens(Data, "\n"),
% Turn "A: B" pairs into "{A, B}" tuples, for searching.
MsgKV = lists:map((fun(Str) ->
list_to_tuple(string:tokens(Str, ": ")) end
), Message),
% Hacky way to build a tuple, filter out not_found later on
Processed = {
case lists:keysearch("Command", 1, MsgKV) of
{value,{_, "define"}} ->
define;
{value,{_, "call"}} ->
call;
{value,{_, "hello"}} ->
hello;
false ->
not_found
end,
case lists:keysearch("Token", 1, MsgKV) of
{value,{_, Value}} ->
Value;
false ->
not_found
end,
case lists:keysearch("Content-Length", 1, MsgKV) of
{value,{_, Value}} ->
{Length, _} = string:to_integer(Value),
[_|Cont] = re:split(Data, "\n\n",[{return,list}]),
Content = string:join(Cont, "\n\n"),
Payload = string:substr(Content,1,Length),
Payload;
false ->
not_found
end
},
gen_server:cast(ggs_server, Processed).
Parsed = do_parse(Data, []),
prettify(Parsed).
do_parse(Data, ParsedMessage) ->
NewLinePos = string:chr(Data, $\n),
Line = string:substr(Data, 1, NewLinePos-1),
Tokens = re:split(Line, ": ", [{return, list}]),
case handle(Tokens) of
{Command, more} ->
do_parse(string:substr(Data, NewLinePos+1), ParsedMessage ++ [Command]);
{separator, data_next} ->
{_, Value} = lists:keyfind(content_len, 1, ParsedMessage),
{ContentLength, []} = string:to_integer(Value),
{ParsedMessage, handle_data(string:substr(Data, NewLinePos+1), ContentLength)}
end.
handle([[]]) ->
{separator, data_next};
handle(["Server-Command", Param]) ->
{{srv_cmd, Param}, more};
handle(["Content-Length", Param]) ->
{{content_len, Param}, more};
handle(["Token", Param]) ->
{{token, Param}, more};
handle(["Content-Type", Param]) ->
{{content_type, Param}, more}.
handle_data(Data, Length) ->
{data, string:substr(Data,1,Length)}.
%% Helpers
prettify({Args, Data}) ->
case lists:keyfind(srv_cmd, 1, Args) of
{_, Value} ->
gen_server:cast(ggs_server, {srv_cmd, Value, Args, Data});
_Other ->
case lists:keyfind(game_cmd, 1, Args) of
{_, Value} ->
gen_server:cast(ggs_server, {game_cmd, Value, Args, Data});
_ ->
ok
end
end.