30 votes

C# iPhone push server ?

J'essaie d'écrire un serveur push pour l'iPhone en C#. J'ai le code suivant :

        // Create a TCP/IP client socket.
        using (TcpClient client = new TcpClient())
        {
            client.Connect("gateway.sandbox.push.apple.com", 2195);
            using (NetworkStream networkStream = client.GetStream())
            {
                Console.WriteLine("Client connected.");

                X509Certificate clientCertificate = new X509Certificate(@"certfile.p12", passwordHere);
                X509CertificateCollection clientCertificateCollection = new X509CertificateCollection(new X509Certificate[1] { clientCertificate });

                // Create an SSL stream that will close the client's stream.
                SslStream sslStream = new SslStream(
                    client.GetStream(),
                    false,
                    new RemoteCertificateValidationCallback(ValidateServerCertificate),
                    null
                    );

                try
                {
                    sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com");
                }
                catch (AuthenticationException e)
                {
                    Console.WriteLine("Exception: {0}", e.Message);
                    if (e.InnerException != null)
                    {
                        Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                    }
                    Console.WriteLine("Authentication failed - closing the connection.");
                    client.Close();
                    return;
                }
            }

ect....

Seulement, je continue à recevoir une exception : "Un appel à SSPI a échoué, voir exception interne". Inner Exception -> "Le message reçu était inattendu ou mal formaté".

Quelqu'un a-t-il une idée de ce qui ne va pas ici ?

8voto

Zenox Points 3723

J'ai compris. Remplacé sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com") ; par sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com", clientCertificateCollection, SslProtocols.Default, false) ; Et enregistré les certificats sur le PC.

Edit : Voici le code pour créer un payload comme demandé :

    private static byte[] GeneratePayload(byte [] deviceToken, string message, string sound)
    {
        MemoryStream memoryStream = new MemoryStream();

        // Command
        memoryStream.WriteByte(0);

        byte[] tokenLength = BitConverter.GetBytes((Int16)32);
        Array.Reverse(tokenLength);
        // device token length
        memoryStream.Write(tokenLength, 0, 2);

        // Token
        memoryStream.Write(deviceToken, 0, 32);

        // String length
        string apnMessage = string.Format ( "{{\"aps\":{{\"alert\":{{\"body\":\"{0}\",\"action-loc-key\":null}},\"sound\":\"{1}\"}}}}",
            message,
            sound);

        byte [] apnMessageLength = BitConverter.GetBytes((Int16)apnMessage.Length);
        Array.Reverse ( apnMessageLength );
        // message length
        memoryStream.Write(apnMessageLength, 0, 2);

        // Write the message
        memoryStream.Write(System.Text.ASCIIEncoding.ASCII.GetBytes(apnMessage), 0, apnMessage.Length);

        return memoryStream.ToArray();
    } // End of GeneratePayload

5voto

Michael Donohue Points 9831

D'après le commentaire de Zenox : utiliser une version différente de AuthenticateAsClient

sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com", clientCertificateCollection, SslProtocols.Default, false);

1voto

shader Points 1312

L'autre moyen consiste à utiliser les classes X509Certificate2 et X509CertificateCollection2.

1voto

tobsen Points 3776

J'ai récemment utilisé Growl pour Windows pour pousser les messages vers le client Prowl sur l'IPhone à partir de code .Net . Ainsi, vous pouvez obtenir votre fonctionnalité sans écrire vous-même un serveur de poussée.

0voto

L'erreur "Le message reçu était inattendu ou mal formaté" survient généralement lorsque vous n'avez pas enregistré le certificat p12 dans Windows. (Sous Vista, il suffit de double-cliquer sur le fichier p12 pour que l'assistant d'importation s'ouvre).

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X