非常简单得mochiweb socket wrap!--?xml version1.0 encodingUTF-8 standaloneno?--写了简单得
非常简单得mochiweb socket wrap
<!--?xml version="1.0" encoding="UTF-8" standalone="no"?-->写了简单得一个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.