How to write an Apple Push Notification Provider in C#?

后端 未结 5 1231
感动是毒
感动是毒 2020-12-02 06:31

Apple really had bad documentation about how the provider connects and communicates to their service (at the time of writing - 2009). I am confused about the protocol. How i

5条回答
  •  爱一瞬间的悲伤
    2020-12-02 07:02

    Working code example:

    int port = 2195;
    String hostname = "gateway.sandbox.push.apple.com";
    
    //load certificate
    string certificatePath = @"cert.p12";
    string certificatePassword = "";
    X509Certificate2 clientCertificate = new X509Certificate2(certificatePath, certificatePassword);
    X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
    
    TcpClient client = new TcpClient(hostname, port);
    SslStream sslStream = new SslStream(
            client.GetStream(),
            false,
            new RemoteCertificateValidationCallback(ValidateServerCertificate),
            null
    );
    
    try
    {
        sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, true);
    }
    catch (AuthenticationException ex)
    {
        client.Close();
        return;
    }
    
    // Encode a test message into a byte array.
    MemoryStream memoryStream = new MemoryStream();
    BinaryWriter writer = new BinaryWriter(memoryStream);
    
    writer.Write((byte)0);  //The command
    writer.Write((byte)0);  //The first byte of the deviceId length (big-endian first byte)
    writer.Write((byte)32); //The deviceId length (big-endian second byte)
    
    String deviceId = "DEVICEIDGOESHERE";
    writer.Write(ToByteArray(deviceId.ToUpper()));
    
    String payload = "{\"aps\":{\"alert\":\"I like spoons also\",\"badge\":14}}";
    
    writer.Write((byte)0); //First byte of payload length; (big-endian first byte)
    writer.Write((byte)payload.Length); //payload length (big-endian second byte)
    
    byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
    writer.Write(b1);
    writer.Flush();
    
    byte[] array = memoryStream.ToArray();
    sslStream.Write(array);
    sslStream.Flush();
    
    // Close the client connection.
    client.Close();
    

提交回复
热议问题