erlang简易web服务器思路

2016-04-06  本文已影响0人  空语

1,开启监控进程 监听端口。gen_tcp:listen(555, Options),其中 Options 选项应为

[    
    {active, false}, 
    binary,
    {backlog, 256},
    {packet, http_bin},
    {raw, 6, 9, <<1:32/nativa\e>>},
    {reuseaddr, true}

]

2spawn_link开启进程 gen_tcp:accept(LisSocket) 获取套接字 Socket,使用 ListenSocket 和 Sockey新建gen_server处理请求3 gen_tcp:recv(Socket, 0, ?MAX_LEN) 获取socket数据 Data 将Data转为list DList,DList的格式为

  [http_request, 'GET', {abs_path, ReuestBin}, _Version]
  [http_request, 'POST', _Requset, _Version]

如为get 则 ReusetBin 为url域名后的文字。自行解析即可
若为post 先获取内容长度

get_content_length(Socket) ->
      case get_tcp:recv(Socket, 0, ?HTTP_TIMEOUT) of
            {ok, {http_header, _, 'Content-Length', _, Length}} ->
                     to_integer(Length);
            {ok, {http_header, _, _Header, _}} ->
                 get_content_length(Socket);
              _ ->         0    
end.
get_post_data(Socket, Length) ->
    case get_tcp:recv(Socket, 0) of       
            {ok, http_eoh} ->
                   inet:setopts(Socket, [{packet, raw}]), 
                   case gen_tcp:recv(Socket, Length) of
                         {ok, Data} ->
                                  decode(Data);
                           _ ->
                              fail
                    end;
             _ ->
                      get_post_data(Socket, Length)
     end.
encode(Term) ->
       iolist_to_binary(io_lib:write(Term)).
decode(Bin) ->
       {ok, T, _} =erl_scan:string(binary_to_list(Bin)++"."),
       {ok, R} = erl_parse:parse_term(T),
      R.
get_cmd_param(Packet) ->
     List =to_list(Packet),
     try
         case string:str(List, "?") of
              0 ->
                   {no_cmd, []};
              N ->
                   CMD = string:substr(List, 2, N-2), %%CMD 为 localhost/zhang?a=d 中的zhang 可为模块名 或处理方法名
                   KVList = kv_list(List),
                   {CMD, KVlist}
         end
     catch
           _:_ -> {no_cmd, []}
end.

4.根据获取的cmd 和Kvlist 进行处理 并返回
5.向浏览器返回结果

send_data(Socket, Data, HttpCode) ->
       Data2 = to_binary(Data),
       Rh = <<"HTTP/1.1", HttpCode/binary, "OK\r\n\r\n">>,
       gen_tcp:send(Socket, <<Rh/binary, Data2/binary>>),
       gen_tcp:close(Socket).
上一篇下一篇

猜你喜欢

热点阅读