cowboy源码分析(一)

前段时间导读了ranch的源码,具体见ranch 源码分析(一)

现在整理了下ranch框架下经典应用cowboy。

源码地方:https://github.com/ninenines/cowboy目前使用的是cowboy-1.0.4版本

 

还是找其中最简单的例子来入手,那就选这个static_world吧~~

 

首先我们来看static_world_app.erl

[root@erlang004 src]# cat static_world_app.erl 
%% Feel free to use, reuse and abuse the code in this file.

%% @private
-module(static_world_app).
-behaviour(application).

%% API.
-export([start/2]).
-export([stop/1]).

%% API.

start(_Type, _Args) ->
    Dispatch = cowboy_router:compile([
        {'_', [
            {"/", cowboy_static, {priv_file, static_world, "index.html"}},
            {"/[...]", cowboy_static, {priv_dir, static_world, "",
                [{mimetypes, cow_mimetypes, all}]}}
        ]}
    ]),
    {ok, _} = cowboy:start_http(http, 100, [{port, 8080}], [
        {env, [{dispatch, Dispatch}]}
    ]),
    static_world_sup:start_link().

stop(_State) ->
    ok.

 

cowboy_router.erl是路径路由设置,我们就不看这个源码,直接看一下结果

1> cowboy_router:compile([
1>         {'_', [
1>             {"/", cowboy_static, {priv_file, static_world, "index.html"}},
1>             {"/[...]", cowboy_static, {priv_dir, static_world, "",
1>                 [{mimetypes, cow_mimetypes, all}]}}
1>         ]}
1>     ]).
[{'_',[],
      [{[],[],cowboy_static,{priv_file,static_world,"index.html"}},
       {['...'],
        [],cowboy_static,
        {priv_dir,static_world,[],
                  [{mimetypes,cow_mimetypes,all}]}}]}]

其实这个路由的意思是如果请求的是/,就路由在priv目录的index.html下面,

否则就直接读取请求的文件。

 

然后我们开始看cowboy:start_http/4,就是应用启动的主进程,

-module(cowboy).

-export([start_http/4]).
-export([start_https/4]).
-export([start_spdy/4]).
-export([stop_listener/1]).
-export([set_env/3]).

%%省略若干行

-spec start_http(ranch:ref(), non_neg_integer(), ranch_tcp:opts(),
    cowboy_protocol:opts()) -> {ok, pid()} | {error, any()}.
start_http(Ref, NbAcceptors, TransOpts, ProtoOpts)
        when is_integer(NbAcceptors), NbAcceptors > 0 ->
    ranch:start_listener(Ref, NbAcceptors,
        ranch_tcp, TransOpts, cowboy_protocol, ProtoOpts).

-spec start_https(ranch:ref(), non_neg_integer(), ranch_ssl:opts(),
    cowboy_protocol:opts()) -> {ok, pid()} | {error, any()}.
start_https(Ref, NbAcceptors, TransOpts, ProtoOpts)
        when is_integer(NbAcceptors), NbAcceptors > 0 ->
    ranch:start_listener(Ref, NbAcceptors,

%%省略若干行
 

 

可以看到这里启动ranch,而cowboy_protocol就是定义的用户进程,根据ranch源码(忘记了的参见ranch源码分析)理解,我们知道会启动cowboy_protocol:start_link/4来处理用户的应用数据请求

下面我们就进入cowboy的代码世界,从cowboy_protocol:start_link/4开始

(未完待续~)

 

转载于:https://www.cnblogs.com/tudou008/p/5652362.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的使用erlang的cowboy框架编写的websocket聊天室代码示例。 ```erlang %% 定义路由和处理函数 -module(chat_router). -behaviour(cowboy_router). -export([init/3]). -export([routes/2]). init(_Transport, _Req, _Opts) -> {ok, [], undefined}. routes(_Req, _State) -> {[ {'_', [ {"/websocket", cowboy_websocket_handler, [ {callback, chat_handler}, {origin, "*"} ]} ]} ], _Req, _State}. %% 定义websocket处理函数 -module(chat_handler). -behaviour(cowboy_websocket_handler). -export([init/3]). -export([websocket_init/3]). -export([websocket_handle/3]). -export([websocket_info/3]). -export([websocket_terminate/3]). init(_TransportName, Req, _Opts) -> {ok, Req, undefined}. websocket_init(_TransportName, Req, _Opts) -> {cowboy_websocket, Req, undefined}. websocket_handle({text, Message}, Req, _State) -> %% 处理收到的文本消息 cowboy_websocket:broadcast(Message, Req), {ok, Req, undefined}; websocket_handle(_Data, Req, _State) -> {ok, Req, undefined}. websocket_info({join, _Pid, _Ref}, Req, _State) -> %% 处理新用户加入聊天室 cowboy_websocket:broadcast("New user joined", Req), {ok, Req, undefined}; websocket_info({leave, _Pid, _Ref}, Req, _State) -> %% 处理用户离开聊天室 cowboy_websocket:broadcast("User left", Req), {ok, Req, undefined}; websocket_info(_Info, Req, _State) -> {ok, Req, undefined}. websocket_terminate(_Reason, Req, _State) -> {ok, Req, undefined}. ``` 以上代码定义了一个路由模块`chat_router`,其中`routes/2`函数指定了处理`/websocket`路径的`cowboy_websocket_handler`处理函数,并将其回调函数指定为`chat_handler`。`chat_handler`模块中的`websocket_handle/3`函数用于处理接收到的文本消息,并使用`cowboy_websocket:broadcast/2`函数将消息广播给所有连接的客户端。`websocket_info/3`函数用于处理新用户加入和离开聊天室的事件,同样使用`cowboy_websocket:broadcast/2`函数将事件广播给所有连接的客户端。 您可以将以上代码保存为`chat.erl`文件,并使用cowboy框架启动websocket服务器,例如: ```erlang %% 启动websocket服务器 -module(chat). -behaviour(application). -export([start/2, stop/1]). start(_Type, _Args) -> Dispatch = cowboy_router:compile([ {'_', [{"/websocket", chat_handler, []}]} ]), {ok, _} = cowboy:start_clear(http, [{port, 8080}], #{env => #{dispatch => Dispatch}}), chat_sup:start_link(). stop(_State) -> ok. ``` 以上代码定义了一个应用模块`chat`,其中`start/2`函数启动了一个cowboy服务器,监听8080端口,并将路由配置为处理`/websocket`路径,使用`chat_handler`处理函数。您可以将以上代码保存为`chat_app.erl`文件,并使用`rebar3`编译和启动应用程序: ```sh $ rebar3 compile $ rebar3 shell ``` 在erlang shell中,您可以使用以下命令连接到websocket服务器并发送消息: ```erlang %% 连接到websocket服务器 1> {ok, Conn} = websocket:connect("ws://localhost:8080/websocket"). {ok,{websocket,#Port<0.7>,<0.198.0>}} %% 发送消息 2> websocket:send_text(Conn, "Hello, World!"). ok ``` 在另一个erlang shell中,您可以使用以下命令连接到相同的websocket服务器并接收消息: ```erlang %% 连接到websocket服务器 1> {ok, Conn} = websocket:connect("ws://localhost:8080/websocket"). {ok,{websocket,#Port<0.7>,<0.203.0>}} %% 接收消息 2> websocket:recv_text(Conn). "New user joined" 3> websocket:recv_text(Conn). "Hello, World!" ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值