2009-06-28 10 views
30

Im tratando de escribir un servidor de inserción para el iPhone en C#. Tengo el siguiente código:C# iPhone push server?

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

Sólo guardo recibir una excepción: "Una llamada a SSPI falló, vea Excepción interna" excepción interna -> "El mensaje recibido fue inesperado o mal formateado ".

¿Alguien tiene alguna idea de lo que está pasando mal aquí?

+6

Lo descubrí. Reemplazado sslStream.AuthenticateAsClient ("gateway.sandbox.push.apple.com"); con sslStream.AuthenticateAsClient ("gateway.sandbox.push.apple.com", clientCertificateCollection, SslProtocols.Default, false); Y registrado los certificados en la PC. – Kyle

+0

Te funcionó? – Zanoni

+0

Sí, tengo todo funcionando y puedo enviar mensajes a mi iPhone. No olvide registrar su archivo .p12 con Windows. – Kyle

Respuesta

8

descubierto. Reemplazado sslStream.AuthenticateAsClient ("gateway.sandbox.push.apple.com"); con sslStream.AuthenticateAsClient ("gateway.sandbox.push.apple.com", clientCertificateCollection, SslProtocols.Default, false); Y registró los certificados en la PC.

Editar: Aquí está el código para crear una carga útil a lo solicitado:

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 
+1

¿Qué carpeta (Certificate Store) debo usar para importar en Windows Server? ¿Es editor personal o de confianza? Intenté "Seleccionar por defecto según el tipo de certificado" pero no funcionó. –

1

Otra forma es simplemente utilizar las clases X509Certificate2 y X509CertificateCollection2.

1

Recientemente utilicé Growl For Windows para enviar mensajes al cliente de Prowl on the IPhone from .Net code. Entonces puede obtener su función sin escribir un servidor de inserción usted mismo.

+0

Eso puede funcionar para enviar datos a la API, pero ¿qué pasa con el manejo de los comentarios? – Kyle

0

El mensaje "El mensaje recibido fue inesperado o mal formateado". Por lo general, el error ocurre cuando no registra el certificado p12 en Windows. (En Vista, haga doble clic en el archivo p12 y el asistente de importación se abrirán)

5

Desde el comentario de Zenox: utilizar una versión diferente de AuthenticateAsClient

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

En mi caso tuve que borrar todo el certificado de mis ventanas 8 y luego volver a instalar el fin de enviar notificaciones push a dispositivo de apple.

No sé por qué mis certificados dejan de funcionar, estoy buscando el motivo correcto y lo actualizaré pronto.