zoukankan      html  css  js  c++  java
  • 非常简单得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.
  • 相关阅读:
    内置函数二
    通信的几个程序
    TCP协议和UDP协议
    异常处理
    logging模块
    网络编程一些概念
    hashlib
    序列化模块
    time,sys,os模块
    random模块
  • 原文地址:https://www.cnblogs.com/bozhang/p/3114700.html
Copyright © 2011-2022 走看看