C#推送信息到APNs的方法

所属分类: 软件编程 / C#教程 阅读数: 39
收藏 0 赞 0 分享

本文实例讲述了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#程序设计有所帮助。

更多精彩内容其他人还在看

winform用datagridview制作课程表实例

这篇文章主要介绍了winform用datagridview制作课程表的方法,实例分析了WinForm实现课程表的结构、数据库及调用技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#中winform控制textbox输入只能为数字的方法

这篇文章主要介绍了C#中winform控制textbox输入只能为数字的方法,包括使用keyPress事件限制键盘输入以及TextChanged事件限制粘贴等情况,来实现控制输入为数字的功能,需要的朋友可以参考下
收藏 0 赞 0 分享

C#省份城市下拉框联动简单实现方法

这篇文章主要介绍了C#省份城市下拉框联动简单实现方法,涉及字典的定义与索引的用法,是非常实用的技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#处理MySql多个返回集的方法

这篇文章主要介绍了C#处理MySql多个返回集的方法,实现了对处理MySql多个返回集进行封装,是非常实用的技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#无限参数的写法

这篇文章主要介绍了C#无限参数的写法,通过循环遍历再结合paras.Add方法实现无限参数的功能,是比较实用的技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#反射应用实例

这篇文章主要介绍了C#反射应用,实例分析了通过反射实现多系统数据库的配置方法,是比较实用的技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#窗体传值实例汇总

这篇文章主要介绍了C#窗体传值,实例形式汇总了静态变量传值、委托传值、对话框之间的传值等常见应用技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#把数组中的某个元素取出来放到第一个位置的实现方法

这篇文章主要介绍了C#把数组中的某个元素取出来放到第一个位置的实现方法,涉及C#针对数组的常见操作技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#中Equality和Identity浅析

这篇文章主要介绍了C#中Equality和Identity浅析,本文先是讲解了Equality和Identity的定义,同时讲解了判断两个对象等价性的4种方法,需要的朋友可以参考下
收藏 0 赞 0 分享

在Linux上运行C#的方法

这篇文章主要介绍了在Linux上运行C#的方法,实例分析了Linux平台下Mono软件包的应用技巧,以及在此基础之上的C#运行方法,具有一定的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多