C#推送信息到APNs的方法

 更新时间:2015年05月06日 11:11:56   作者:chenzym  
这篇文章主要介绍了C#推送信息到APNs的方法,涉及C#推送通知到苹果APNs的实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了C#推送信息到APNs的方法。分享给大家供大家参考。具体实现方法如下:

class Program
{
  public static DateTime? Expiration { get; set; }
  public static readonly DateTime DoNotStore = DateTime.MinValue;
  private static readonly DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  private static string DeviceToken = "273eeddaef02192cf4ba5b666453b258f2d2a1ad02f549105fd03fea789d809d";
  public const int DEVICE_TOKEN_BINARY_SIZE = 32;
  public const int DEVICE_TOKEN_STRING_SIZE = 64;
  public const int MAX_PAYLOAD_SIZE = 256;
  private static X509Certificate certificate;
  private static X509CertificateCollection certificates;
  static void Main(string[] args)
  {
   string hostIP = "gateway.sandbox.push.apple.com";//
   int port = 2195;
   string password = "ankejiaoyu";//
   string certificatepath = "aps_developer_identity.p12";//bin/debug
   string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, certificatepath);
   certificate = new X509Certificate2(System.IO.File.ReadAllBytes(p12Filename), password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
   certificates = new X509CertificateCollection();
   certificates.Add(certificate);
   TcpClient apnsClient = new TcpClient();
   apnsClient.Connect(hostIP, port);
   SslStream apnsStream = new SslStream(apnsClient.GetStream(), false, new RemoteCertificateValidationCallback(validateServerCertificate), new LocalCertificateSelectionCallback(selectLocalCertificate));
   try
   {
    //APNs已不支持SSL 3.0 
    apnsStream.AuthenticateAsClient(hostIP, certificates, System.Security.Authentication.SslProtocols.Tls, false);
   }
   catch (System.Security.Authentication.AuthenticationException ex)
   {
    Console.WriteLine("error+"+ex.Message);
   }
   if (!apnsStream.IsMutuallyAuthenticated)
   {
    Console.WriteLine("error:Ssl Stream Failed to Authenticate!");
   }
   if (!apnsStream.CanWrite)
   {
    Console.WriteLine("error:Ssl Stream is not Writable!");
   }
   Byte[] message = ToBytes();
   apnsStream.Write(message);
  }
  public static byte[] ToBytes()
  {
   // Without reading the response which would make any identifier useful, it seems silly to
   // expose the value in the object model, although that would be easy enough to do. For
   // now we'll just use zero.
   int identifier = 0;
   byte[] identifierBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(identifier));
   // APNS will not store-and-forward a notification with no expiry, so set it one year in the future
   // if the client does not provide it.
   int expiryTimeStamp = -1;//过期时间戳
   if (Expiration != DoNotStore)
   {
    //DateTime concreteExpireDateUtc = (Expiration ?? DateTime.UtcNow.AddMonths(1)).ToUniversalTime();
    DateTime concreteExpireDateUtc = (Expiration ?? DateTime.UtcNow.AddSeconds(20)).ToUniversalTime();
    TimeSpan epochTimeSpan = concreteExpireDateUtc - UNIX_EPOCH;
    expiryTimeStamp = (int)epochTimeSpan.TotalSeconds;
   }
   byte[] expiry = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(expiryTimeStamp));
   byte[] deviceToken = new byte[DeviceToken.Length / 2];
   for (int i = 0; i < deviceToken.Length; i++)
    deviceToken[i] = byte.Parse(DeviceToken.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
   if (deviceToken.Length != DEVICE_TOKEN_BINARY_SIZE)
   {
    Console.WriteLine("Device token length error!");
   }
   byte[] deviceTokenSize = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(Convert.ToInt16(deviceToken.Length)));
   string str = "{\"aps\":{\"alert\":\"这是测试消息!!\",\"badge\":1,\"sound\":\"anke.mp3\"}}";
   byte[] payload = Encoding.UTF8.GetBytes(str);
   byte[] payloadSize = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(Convert.ToInt16(payload.Length)));
   List<byte[]> notificationParts = new List<byte[]>();
   //1 Command
   notificationParts.Add(new byte[] { 0x01 }); // Enhanced notification format command
   notificationParts.Add(identifierBytes);
   notificationParts.Add(expiry);
   notificationParts.Add(deviceTokenSize);
   notificationParts.Add(deviceToken);
   notificationParts.Add(payloadSize);
   notificationParts.Add(payload);
   return BuildBufferFrom(notificationParts);
  }
  private static byte[] BuildBufferFrom(IList<byte[]> bufferParts)
  {
   int bufferSize = 0;
   for (int i = 0; i < bufferParts.Count; i++)
    bufferSize += bufferParts[i].Length;
   byte[] buffer = new byte[bufferSize];
   int position = 0;
   for (int i = 0; i < bufferParts.Count; i++)
   {
    byte[] part = bufferParts[i];
    Buffer.BlockCopy(bufferParts[i], 0, buffer, position, part.Length);
    position += part.Length;
   }
   return buffer;
  }
  private static bool validateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
  {
   return true; // Dont care about server's cert
  }
  private static X509Certificate selectLocalCertificate(object sender, string targetHost, X509CertificateCollection localCertificates,
   X509Certificate remoteCertificate, string[] acceptableIssuers)
  {
   return certificate;
  }
}

希望本文所述对大家的C#程序设计有所帮助。

相关文章

  • Unity编辑器资源导入处理函数OnPostprocessAudio使用案例

    Unity编辑器资源导入处理函数OnPostprocessAudio使用案例

    这篇文章主要为大家介绍了Unity编辑器资源导入处理函数OnPostprocessAudio使用案例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-08-08
  • C#中类与结构的区别实例分析

    C#中类与结构的区别实例分析

    这篇文章主要介绍了C#中类与结构的区别,类与结构是C#初学者比较轻易混淆的概念,本文加以实例说明,需要的朋友可以参考下
    2014-08-08
  • WPF利用DrawingContext实现绘制温度计

    WPF利用DrawingContext实现绘制温度计

    这篇文章主要为大家详细介绍了如何利用WPF和DrawingContext实现绘制温度计,文中的示例代码讲解详细,对我们学习或工作有一定帮助,感兴趣的小伙伴可以了解一下
    2022-09-09
  • 基于JWT.NET的使用(详解)

    基于JWT.NET的使用(详解)

    下面小编就为大家分享一篇基于JWT.NET的使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-12-12
  • C#实现批量Word转换Html的示例代码

    C#实现批量Word转换Html的示例代码

    这篇文章主要为大家详细介绍了如何利用C#批量Word转换Html的功能,文中的示例代码讲解详细,对我们学习C#有一定的帮助,感兴趣的小伙伴可以跟随小编一起了解一下
    2022-12-12
  • C# 使用Word模板导出数据的实现代码

    C# 使用Word模板导出数据的实现代码

    最近接到个需求,使用word模板导出数据,怎么实现这个需求呢,今天小编通过实例代码给大家介绍C# 使用Word模板导出数据的方法,感兴趣的朋友一起看看吧
    2021-06-06
  • C#实现网页画图功能

    C#实现网页画图功能

    这篇文章主要为大家详细介绍了C#实现网页画图功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-03-03
  • C#检测上传文件真正类型的方法

    C#检测上传文件真正类型的方法

    这篇文章主要介绍了C#检测上传文件真正类型的方法,可有效的防止用户通过修改后缀名来改变文件类型的功能,需要的朋友可以参考下
    2015-04-04
  • C#中委托和事件的区别详解

    C#中委托和事件的区别详解

    C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。事件是在委托类型变量前加上 event 关键字,其本质是用来对委托类型的变量进行封装,类似于类的属性对字段的封装。本文就来聊聊C#中委托和事件的区别,感兴趣的可以了解一下
    2022-11-11
  • 在C#中调用VBScript、javascript等脚本的实现代码

    在C#中调用VBScript、javascript等脚本的实现代码

    在C#中调用VBScript、javascript等脚本的实现步骤,需要的朋友可以参考下。
    2009-11-11

最新评论