Erlang Apple Push通知在断开连接之前没有收到响应错误

时间:2012-05-19 17:36:56

标签: ssl erlang apple-push-notifications gen-server

我目前正在测试我的推送通知模块。 当设备令牌无效时,它会断开连接......

根据Apple push notification developer documentation我应该在苹果推送服务器断开之前收到错误响应数据包...

事情是我断开连接,但是在此之前我没有在Socket上得到任何东西,我需要知道推送是否因为推送错误(因此我可以修复错误)或无效设备而失败令牌(所以我可以将其从数据库中删除)。

这是我的代码:

-module(pushiphone).
-behaviour(gen_server).

-export([start/1, init/1, handle_call/3, handle_cast/2, code_change/3, handle_info/2, terminate/2]).

-import(ssl, [connect/4]).
-record(push, {socket, state, cert, key}).

start(Provisioning) ->
    gen_server:start_link(?MODULE, [Provisioning], []).

init([Provisioning]) ->
    gen_server:cast(self(), {connect, Provisioning}),
    {ok, #push{}}.

send(Socket, DT, Payload) ->
    PayloadLen = length(Payload),
    DTLen = size(DT),
    PayloadBin = list_to_binary(Payload),
    Packet = <<0:8, 
           DTLen:16/big, 
           DT/binary, 
           PayloadLen:16/big, 
           PayloadBin/binary>>,
    ssl:send(Socket, Packet).

handle_call(_, _, P) ->
    {noreply, P}.

handle_cast({connect, Provisioning}, P) ->
    case Provisioning of
    dev -> Address = "gateway.sandbox.push.apple.com";
    prod -> Address = "gateway.push.apple.com"
    end,
    Port = 2195,
    Cert="/apns-" ++ atom_to_list(Provisioning) ++ "-cert.pem",
    Key="/apns-" ++ atom_to_list(Provisioning) ++ "-key.pem",
    Options = [{certfile, Cert}, {keyfile, Key}, {password, "********"}, {mode, binary}, {active, true}],
    Timeout = 1000,
    {ok, Socket} = ssl:connect(Address, Port, Options, Timeout),
    {noreply, P#push{socket=Socket}};
handle_cast(_, P) ->
    {noreply, P}.

handle_info({ssl, Socket, Data}, P) ->
    <<Command, Status, SomeID:32/big>> = Data,
    io:fwrite("[PUSH][ERROR]: ~p / ~p / ~p~n", [Command, Status, SomeID]),
    ssl:close(Socket),
    {noreply, P};
handle_info({push, message, DT, Badge, [Message]}, P) ->
    Payload = "{\"aps\":{\"alert\":\"" ++ Message ++ "\",\"badge\":" ++ Badge ++ ",\"sound\":\"" ++ "msg.caf" ++ "\"}}",
    send(P#push.socket, DT, Payload),
    {noreply, P};
handle_info({ssl_closed, _SslSocket}, P) ->
    io:fwrite("SSL CLOSED !!!!!!~n"),
    {stop, normal, P};
handle_info(AnythingElse, P) ->
    io:fwrite("[ERROR][PUSH][ANYTHING ELSE] : ~p~n", [AnythingElse]),
    {noreply, P}.

code_change(_, P, _) ->
    {ok, P}.

terminate(_, _) ->
    ok.

当有效负载和deviceToken都正确时,它工作得很好。如果deviceToken无效,则只会断开连接。

有没有人能发现这个问题?因为经过4个小时的搜索,我才发现我显然不能!

这是错误响应表:

Status code     Description
0           No errors encountered
1           Processing error
2           Missing device token
3           Missing topic
4           Missing payload
5           Invalid token size
6           Invalid topic size
7           Invalid payload size
8           Invalid token
255         None (unknown)

1 个答案:

答案 0 :(得分:1)

您似乎正在使用您链接到的Apple文档中图5-1所定义的简单通知格式(根据您的send()函数判断)。使用此格式时,如果请求格式错误,则不会提供错误响应 - 您只需断开连接。

要获得错误响应,您应该使用图5-2中详细说明的增强通知格式