Gen_tcp 超过 gen_server 套接字侦听立即关闭

Gen_tcp over gen_server socket listen closed immediatly

我想在 gen_server 上使用 gen_tcp,代码如下:

start_link() ->
 io:format("start_link~n"),
 gen_server:start_link({global, ?MODULE}, ?MODULE, [], []).

init([])  ->
 {ok,ListenSocket} = gen_tcp:listen(8091, [{active,true}, binary]),
 io:format("listen done ~p ~p pid: ~p ~n",[ok,ListenSocket,self()]),
 %here the listen is closed
 waitConnection(),
 {ok,#state{listenSocket = ListenSocket}}.

handle_cast(waitConnection, #state{listenSocket = ListenSocket}) ->
 io:format("cast wait connections ~p pid:~p   ~n",[ListenSocket,self()]),
 {ok,Socket} = gen_tcp:accept(ListenSocket),
 io:format("cast wait accept ~n"),
 Pid = spawn(?MODULE,get_request,[Socket,[]]),
 gen_tcp:controlling_process(Socket,Pid),
 waitConnection(),
 {noreply, ListenSocket}.

waitConnection() ->
 try gen_server:cast({global, ?MODULE}, waitConnection)
 catch
   exit:{_,_} -> io:format("errror")
 end.

嗯,tcp_listenerwaitConnetion之前就直接关闭了,我真的不明白为什么。

如果我移动初始化部分的 handle_cast 代码,它会正常工作。

为什么连接被关闭了?我花了很多时间都没有成功。

感谢任何帮助。

编辑:

如果我将转换代码移到侦听器之后:

lsof -i :8091
    COMMAND   PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
    beam.smp 6402 JR   24u  IPv4 0x9544c4111122e613      0t0  TCP *:8091 (LISTEN)

我发布的代码:

lsof -i :8091
// is empty

好的,我解决了:

handle_cast(waitConnection, State = #state{listenSocket = ListenSocket}) ->
    io:format("ListenSocket ok ~n"),
    {ok,Socket} = gen_tcp:accept(ListenSocket),
    io:format("cast wait accept ~n"),
    Pid = spawn(?MODULE,get_request,[Socket,[]]),
    gen_tcp:controlling_process(Socket,Pid),
    waitConnection(),
    {noreply, State}.

问题是 "State" 参数。

谢谢大家