如何使用C#从APNS获取通知响应

Hin*_*man 3 c# push-notification apple-push-notifications ios

我正在创建一个web api应用程序,我想向iOS设备发送通知.

我尝试过使用pushsharp,但它只适用于少量设备,同时将其发送到具有过期/无效令牌的多个设备,而不是向所有设备发送通知.

所以,我将使用以下代码:

public async Task pushMessage(string deviceToken, string message)
{
  int port = 2195;
  String hostname = "gateway.sandbox.push.apple.com";

  String certificatePath = "~/test.p12" // my certificate path 

  X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), CommonSource.GetAppleCertificatePassword(), X509KeyStorageFlags.MachineKeySet);
  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, false);
     MemoryStream memoryStream = new MemoryStream();
     BinaryWriter writer = new BinaryWriter(memoryStream);
     writer.Write((byte)0);
     writer.Write((byte)0);
     writer.Write((byte)32);

     writer.Write(HexStringToByteArray(deviceToken.ToUpper()));    
     String payload = message.ToString(); 

     writer.Write((byte)0);
     writer.Write((byte)payload.Length);
     byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
     writer.Write(b1);
     writer.Flush();
     byte[] array = memoryStream.ToArray();
     sslStream.Write(array);
     sslStream.Flush();

     // Read message from the server. 
     //byte[] response = ReadMessage(sslStream);   

     client.Close();
   }
  catch (System.Security.Authentication.AuthenticationException ex)
  {
     LogError(ex.Message);
     client.Close();
  }
  catch (Exception e)
  {
    LogError(e.Message);
    client.Close();
   }            
} 
Run Code Online (Sandbox Code Playgroud)

这段代码正是我想要的.
但现在我想检查来自APNS服务器的响应.所以我用byte[] response = ReadMessage(sslStream); And ReadMessage方法检查了如下:

private byte[] ReadMessage(SslStream sslStream)
{
    MemoryStream ms = new MemoryStream();

    byte[] buffer = new byte[1024];

    int bytes = -1;
    do
    {
        bytes = sslStream.Read(buffer, 0, buffer.Length);

        ms.Write(buffer, 0, bytes);

    } while (bytes != 0);

    return ms.ToArray();
}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行它时,它坚持bytes = sslStream.Read(buffer, 0, buffer.Length); 我无法弄清楚问题.

谁能告诉我,我的代码有什么问题?

Nko*_*osi 5

根据这篇文章

苹果推送通知服务的问题...解决方案和解决方法......

  1. Apple从未对成功的消息发送响应.

  2. 在您有机会向流发送更多通知之前,但在Apple关闭连接之前,可能不会立即返回错误响应.这些可能仍然"通过"的通知仍处于不确定状态.它们永远不会被确认或交付,也不会为它们返回错误响应.

因此,如果您的请求按预期工作,则不会有任何响应.这意味着您尝试阅读响应将无法获得任何内容,这是您在无法通过读取线时遇到的情况.它正在等待可能永远不会到来的响应.