非常简单得mochiweb socket wrap

写了简单得一个socket 接口,就是把mochiweb里socket部分抽取出来了。

 
mochiweb_socket_wrap.erl:
 
%%%-------------------------------------------------------------------
%%% @author zhangbo <>
%%% @copyright (C) 2011, zhangbo
%%% @doc
%%%
%%% @end
%%% Created : 28 Dec 2011 by zhangbo <>
%%%-------------------------------------------------------------------
-module(mochiweb_socket_wrap).
 
-compile(export_all).
 
-define(DEFAULTS, [{name, ?MODULE},
                   {port, 8889}]).
 
start() ->
    %% insert your callback loop here
    CallbackLoop = fun() ->
                           io:format("CallbackLoop fun is called~n", [])
                   end,
   
    Loop = fun (S) ->
                   ?MODULE:loop(S, CallbackLoop)
           end,
    Options1 = [{ip, "127.0.0.1"}, {loop, Loop}],
    Options = mochilists:set_defaults(?DEFAULTS, Options1),
    mochiweb_socket_server:start(Options).
 
stop() ->
    mochiweb_socket_server:stop(?MODULE).
 
 
loop(S, CallbackLoop) ->
    io:format("loop~n", []),
    ok = mochiweb_socket:setopts(S, [{active, once}]),
    %% inet:setopts(S, [{nodelay,true}, {active, true}]),
    try
        receive
            {tcp, S, Bin} ->
                io:format("Bin:~p~n",[Bin]),
                CallbackLoop(),
                loop(S, CallbackLoop);
            {tcp_closed,S} ->
                io:format("Socket ~p is closed~n",[S]),
                gen_tcp:close(S);
            Any ->
                io:format("Any:~p~n",[Any]),
                loop(S, CallbackLoop)
        end
    catch
        _:X ->
            io:format("Exception:~p:~p~n",[X, erlang:get_stacktrace()]),
            {X, erlang:get_stacktrace()}
    end.

posted on 2013-06-03 09:11  Bo.Zhang  阅读(175)  评论(0编辑  收藏  举报