当前位置: 代码迷 >> Web前端 >> 十分简单得mochiweb socket wrap
  详细解决方案

十分简单得mochiweb socket wrap

热度:549   发布时间:2012-09-12 09:21:30.0
非常简单得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.
  相关解决方案