0

我想在 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_listener之前立即关闭waitConnetion,我真的不明白为什么。

如果我handle_cast在 init 部分移动代码,它可以正常工作。

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

任何帮助表示赞赏。

编辑

如果我在听众之后移动演员代码:

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
4

1 回答 1

0

好的,我解决了:

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}.

问题是“状态”参数。

谢谢你们

于 2015-07-28T20:51:42.673 回答