# IPhone C empurrar servidor?
-
20-08-2019 - |
Pergunta
Im tentando escrever um servidor de envio para o iPhone em C #. Eu tenho o seguinte código:
// 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 ....
Apenas eu continuo recebendo uma exceção: "Uma chamada para SSPI falhou, ver exceção Inner" Exceção interna -> "A mensagem recebida foi inesperada ou mal formatado."
Alguém tem alguma idéia o que está acontecendo de errado aqui?
Solução
Descobri-lo. Substituído sslStream.AuthenticateAsClient ( "gateway.sandbox.push.apple.com"); com sslStream.AuthenticateAsClient ( "gateway.sandbox.push.apple.com", clientCertificateCollection, SslProtocols.Default, false); E registrado os certificados no PC.
Edit: Aqui está o código para criar uma carga útil, conforme 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
Outras dicas
Desde o comentário de Zenox: usar uma versão diferente do AuthenticateAsClient
sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com", clientCertificateCollection, SslProtocols.Default, false);
Outra maneira é só para usar classes X509Certificate2 e X509CertificateCollection2.
Eu usei recentemente Growl para Windows para empurrar mensagens para o cliente Prowl no código IPhone da Net . Então você pode obter o seu functionatlity sem escrever um servidor de envio si mesmo.
O "A mensagem recebida foi inesperada ou mal formatado." erro geralmente vem quando você não registrar o certificado p12 no Windows. (Sob Vista, basta clicar duas vezes sobre o arquivo p12 e o assistente de importação será aberta)
No meu caso eu tive que apagar todo o certificado do meu windows 8 e, em seguida, reinstalá-los, a fim de enviar notificações push para o dispositivo da Apple.
Eu não sei por que meus certificados parar de trabalhar, eu estou procurando a razão correta e irá atualizar aqui em breve.