计算APNS帧大小/格式化字节流

时间:2015-05-06 20:36:35

标签: java ios apple-push-notifications javaapns

根据[https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW4],正确的通知格式如下:

OutputStream os; // assuming this connection is valid/open

// header
os.write(command);        // 1 byte    | value of 2 in doc but 1 in notnoop/java-apns ?
os.write(frame_length);   // 4 bytes   | value of total size of frame items:

// item 1 - token
os.write(item_id_1);      // 1 byte    | value of 1
os.write(item_length_1);  // 2 bytes   | value of size of data (32 for token):
os.write(item_data_1);    // 32 bytes  | token data
// = total frame item size: 35

// item 2 - payload
os.write(item_id_2);      // 1 byte    | value of 2
os.write(item_length_2);  // 2 bytes   | value of size of data (175 for my payload):
os.write(item_data_2);    // 175 bytes | payload data
// = total frame item size: 178

// item 3 - identifier
os.write(item_id_3);      // 1 byte    | value of 3
os.write(item_length_3);  // 2 bytes   | value of size of data (4)
os.write(item_data_3);    // 4 byte    | identifier data
// = total frame item size: 7

// item 4 - expiration date
os.write(item_id_4);      // 1 byte    | value of 4
os.write(item_length_4);  // 2 bytes   | value of size of data (4)
os.write(item_data_4);    // 4 byte    | expiration data
// = total frame item size: 7

// item 5 - priority
os.write(item_id_5);      // 1 byte    | value of 5
os.write(item_length_5);  // 2 bytes   | value of size of data (1):
os.write(item_data_5);    // 1 byte    | priority data
// = total frame item size: 4

假设这一切都是正确的,那么通过对所有帧项目总数求和,它应该给出一个帧数据总长度:35 + 178 + 7 + 7 + 4 = 232

然而,查看一些notnoop/java-apns code

    public byte[] marshall() {
        if (marshall == null) {
            marshall = Utilities.marshallEnhanced(COMMAND, identifier,
                    expiry, deviceToken, payload);
        }
        return marshall.clone();
    }

    public int length() {
        int length = 1 + 4 + 4 + 2 + deviceToken.length + 2 + payload.length;

        //1 = ?
        //4 = identifier length
        //4 = expiration length
        //2 = ?
        //32 = token length
        //2 = ?
        //x = payload length

        final int marshalledLength = marshall().length;
        assert marshalledLength == length;
        return length;
    }

我没有看到这是如何正确计算长度的。然而,我的代码无法正常工作。我做错了什么?

1 个答案:

答案 0 :(得分:0)

  • 第一个问题:在尝试使用新格式(uses command 1)时,我正在检查增强格式(uses command 2)。

  • 第二个问题:我没有使用某种形式的ByteBuffer ing ,因此数据包形成不正确。

两种情况下的总帧大小计算都是正确的。