Erlang中文论坛

标题: ranch初窥3 [打印本页]

作者: 茶叶feng    时间: 2018-7-13 17:27
标题: ranch初窥3
# 接《ranch初窥2》#
- 从我的有道云笔记转过来的, 可以直接访问连接http://note.youdao.com/noteshare?id=20b0bc4806aed935da3f258816eae7da&sub=AF84BFF80C114F3898D6FC07648EEC99
## ranch_acceptors_sup.erl ##
从ranch\_server中获取ranch\_conns\_sup的进程,并且获取监听参数TransOpts,如果ranch\_server中尚未有监听socket,则启动监听socket,接着把监听socket记录到ranch\_server中,启动一个ranch\_acceptor子进程。

## ranch_acceptor.erl ##
启动一个loop/3循环,当接收到客户端的socket之后,把socket的控制进程改为连接监控进程ranch\_conns\_sup,连接监控进程中有对应的一些消息处理,接着调用ranch\_conns\_sup:start\_protocol/2发送{?MODULE, start\_protocol, self(), Socket},ranch\_conns\_sup进程自身对该消息进行处理,详情看ranch\_conns\_sup.erl的介绍,至此,ranch的监听端口的工作都已经准备完毕,(发现还有部分忽略了,需要实现ranch_protocol行为才能处理客户端消息的)现在就差客户端的连接进来了。
```
-spec loop(inet:socket(), module(), pid()) -> no_return().
loop(LSocket, Transport, ConnsSup) ->
        _ = case Transport:accept(LSocket, infinity) of
                {ok, CSocket} ->
                        case Transport:controlling_process(CSocket, ConnsSup) of
                                ok ->
                                        %% This call will not return until process has been started
                                        %% AND we are below the maximum number of connections.
                                        ranch_conns_sup:start_protocol(ConnsSup, CSocket);
                                {error, _} ->
                                        Transport:close(CSocket)
                        end;
                %% Reduce the accept rate if we run out of file descriptors.
                %% We can't accept anymore anyway, so we might as well wait
                %% a little for the situation to resolve itself.
                {error, emfile} ->
                        error_logger:warning_msg("Ranch acceptor reducing accept rate: out of file descriptors~n"),
                        receive after 100 -> ok end;
                %% We want to crash if the listening socket got closed.
                {error, Reason} when Reason =/= closed ->
                        ok
        end,
        flush(),
        ?MODULE:loop(LSocket, Transport, ConnsSup).
```






欢迎光临 Erlang中文论坛 (https://bbs.erldoc.com/) Powered by Discuz! X3.3