erlangejabberderlang-supervisorejabberd-module

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.

My question is:


Solution

  • Messages sent to a gen_server process, e.g. GenServerPid ! {ok, 10}}, are handled by:

    handle_info(Msg, State)
    

    So, you could do something like this:

    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.
    

    Response to comment:

    This is your current code:

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

    You could change that to something like this:

    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().
      
    

    After you start the apns process, the apns process will enter a loop and wait for messages.