如何接收发送到 gen_server 内 运行 的 PID 的消息

How can I receive messages sent to a PID which running inside a gen_server

If network goes down or something unexpected happens the gun connection with APNs will go down. In that case apns4erl will send a message {reconnecting, ServerPid} to the client process, that means apns4erl lost the connection and it is trying to reconnect. Once the connection has been recover a {connection_up, ServerPid} message will be send.

我的问题是:

发送到 gen_server 进程的消息,例如GenServerPid ! {ok, 10}},由以下人员处理:

handle_info(Msg, State)

所以,你可以这样做:

handle_info({reconnecting, ServerPid}=Msg, State) ->
     %%do something here, like log Msg or change State;
handl_info({connection_up, ServerPid}=Msg, State) ->
     %%do something here, like log Msg or change State;   
handle_info(#offline_msg{us = _UserServer,
          from = From, to = To, packet = Packet} = _Msg, State) ->
     %%do something.

回复评论:

这是您当前的代码:

init([Host, _Opts]) ->
      apns:start(),
      case apns:connect(cert, ?APNS_CONNECTION) of
           {ok, PID} -> ?INFO_MSG("apns connection successful with PID ~p~n", [PID]);
           {error, timeout} -> ?ERROR_MSG("apns connection unsuccessful reason timed out", [])
      end,
      {ok, #state{host = Host}}.

你可以把它改成这样:

init([Host, _Opts]) ->
    spawn(?MODULE, start_apns, []),
    ...


start_apns() ->

          apns:start(),
          case apns:connect(cert, ?APNS_CONNECTION) of
               {ok, PID} -> ?INFO_MSG("apns connection successful with PID ~p~n", [PID]);
               {error, timeout} -> ?ERROR_MSG("apns connection unsuccessful reason timed out", [])
          end,
          apns_loop().

apns_loop() ->
    receive
        {reconnecting, ServerPid} -> %%do something;
        {connection_up, ServerPid} -> %% do something;
        Other -> %% do something
    end,
    apns_loop().
  

启动apns进程后,apns进程会进入循环等待消息