我用牧场听插座,但是在短时间内大约五秒钟,牧场关闭了插座,我的插座设置在上面,所以'错?
{ok, _} = ranch:start_listener(server,200, ranch_tcp, [{port, 5555},{active, once}, {max_connections, 1024}], server_protocol, []), %% start the listener
协议文件在下面,牧场监听接受套接字,反之接收数据,但错误的是,当将数据发送回客户端时,大约五秒后,客户端收到消息说套接字由服务器关闭,我不知道牧场的默认设置是否导致这个?
-module(reverse_protocol).
-behaviour(gen_server).
-behaviour(ranch_protocol).
%% API.
-export([start_link/4]).
%% gen_server.
-export([init/1]).
-export([init/4]).
-export([handle_call/3]).
-export([handle_cast/2]).
-export([handle_info/2]).
-export([terminate/2]).
-export([code_change/3]).
-define(TIMEOUT, 5000).
-record(state, {socket, transport}).
%% API.
start_link(Ref, Socket, Transport, Opts) ->
proc_lib:start_link(?MODULE, init, [Ref, Socket, Transport, Opts]).
%% gen_server.
%% This function is never called. We only define it so that
%% we can use the -behaviour(gen_server) attribute.
init([]) -> {ok, undefined}.
init(Ref, Socket, Transport, _Opts = []) ->
ok = proc_lib:init_ack({ok, self()}),
ok = ranch:accept_ack(Ref),
ok = Transport:setopts(Socket, [{active, once}]),
gen_server:enter_loop(?MODULE, [],
#state{socket=Socket, transport=Transport},
?TIMEOUT).
handle_info({tcp, Socket, Data}, State=#state{
socket=Socket, transport=Transport}) ->
Transport:setopts(Socket, [{active, once}]),
Transport:send(Socket, reverse_binary(Data)),
{noreply, State, ?TIMEOUT};
handle_info({tcp_closed, _Socket}, State) ->
{stop, normal, State};
handle_info({tcp_error, _, Reason}, State) ->
{stop, Reason, State};
handle_info(timeout, State) ->
{stop, normal, State};
handle_info(_Info, State) ->
{stop, normal, State}.
handle_call(_Request, _From, State) ->
{reply, ok, State}.
handle_cast(_Msg, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% Internal.
reverse_binary(B) when is_binary(B) ->
[list_to_binary(lists:reverse(binary_to_list(
binary:part(B, {0, byte_size(B)-2})
))), "\r\n"].
答案 0 :(得分:2)
所以你的问题是因为你的gen_server进程正在超时并关闭。正在关闭的套接字是一个副作用,因为ranch将Socket链接到生成的处理程序进程。
一旦新进程通过调用gen_server:enter_loop
进入gen_server循环,在发送?TIMEOUT
消息之前,它有timeout
毫秒的时间来接收消息。
-define(TIMEOUT, 5000).
init(Ref, Socket, Transport, _Opts = []) ->
ok = proc_lib:init_ack({ok, self()}),
ok = ranch:accept_ack(Ref),
ok = Transport:setopts(Socket, [{active, once}]),
gen_server:enter_loop(?MODULE, [],
#state{socket=Socket, transport=Transport},
?TIMEOUT). %% timeout because of this!
handle_info({tcp, Socket, Data}, State=#state{
socket=Socket, transport=Transport}) ->
Transport:setopts(Socket, [{active, once}]),
Transport:send(Socket, reverse_binary(Data)),
{noreply, State, ?TIMEOUT}; %% timeout because of this!
因此,当那五秒钟传递并且gen_server在那段时间内没有收到任何消息时,它会发送一条timeout
消息,然后由handle_info
处理
handle_info(timeout, State) ->
{stop, normal, State};
你的handle_info
告诉gen_server停止,这会导致Socket关闭,因为这两个链接在一起。
您可以完全删除超时,也可以暂停超时以使进程关闭。
以下是我将如何更改handle_info
超时代码:
handle_info(timeout, State) ->
io:format("the socket is idle~n"),
{noreply,State};