• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >C#教程 > C#推送信息到APNs的方法

C#推送信息到APNs的方法

作者:chenzym 字体:[增加 减小] 来源:互联网 时间:2017-05-28

chenzym 通过本文主要向大家介绍了apns推送,apns推送证书,亚马逊 apns,apns,apns 003等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

本文实例讲述了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;
  }
}
</div>

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

</div>
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • C#推送信息到APNs的方法

相关文章

  • 2017-05-28C# 参考之访问关键字:base、this
  • 2017-05-28C#中前台线程和后台线程的区别与联系
  • 2017-05-28C#:foreach与yield语句的介绍
  • 2017-05-28linq语法基础使用示例
  • 2017-05-28C#中Response.Write常见问题汇总
  • 2017-05-28C#中动态数组用法实例
  • 2017-05-28C#使用WebService结合jQuery实现无刷新翻页的方法
  • 2017-05-28C# winform打开Excel文档的方法总结(必看篇)
  • 2017-05-28C#使用Ado.net读取Excel表的方法
  • 2017-05-28C#事件处理和委托event delegate实例简述

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • C#自写的一个HTML解析类(类似XElement语法)
    • C#中fixed关键字的作用总结
    • C#实现只运行单个实例应用程序的方法(使用VB.Net的IsSingleInstance)
    • C# Winform多屏幕多显示器编程技巧实例
    • 未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序解决办法
    • C#词法分析器之转换DFA详解
    • C#实现协同过滤算法的实例代码
    • C# 超高面试题收集整理
    • 深入Ref,Out的理解及其使用
    • C#中datagridview使用tooltip控件显示单元格内容的方法

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有