public class AppleAPNSMessage
{
/// <summary>
/// 苹果信息推送 证书 路径(注意测试版跟正式发布版证书上不一样)
/// </summary>
private static string cerPath = ConfigurationManager.AppSettings["CerPath"];
/// <summary>
/// 苹果推送服务 密码
/// </summary>
private static string msgPushPWD = ConfigurationManager.AppSettings["MSGPushPWD"];
/// <summary>
/// 苹果推送服务 开关
/// open:开 close:关
/// </summary>
private static string msgPushSwitch = ConfigurationManager.AppSettings["MSGPushSwitch"];
/// <summary>
/// 苹果消息推送 请求地址 产品正式版:gateway.push.apple.com 测试环境:gateway.sandbox.push.apple.com
/// </summary>
private static string iosHostUrl = ConfigurationManager.AppSettings["iosHostUrl"];
/// <summary>
/// 苹果消息推送 请求端口
/// </summary>
private static string iosHostPort = ConfigurationManager.AppSettings["iosHostPort"]; 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);
public static string DeviceToken = "";//;//苹果设备token
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;
public static string apnsMessage = "测试内容!!";
/// <summary>
/// 发送消息
/// </summary>
public static void SendMessage()
{
//苹果推送开关
if (msgPushSwitch == "close")
{
return;
}
string hostIP = iosHostUrl;//"gateway.push.apple.com";//"gateway.sandbox.push.apple.com";//
int port = int.Parse(iosHostPort);
string password = string.Empty;
string certificatepath = string.Empty;
password = msgPushPWD;//"123456";
certificatepath = cerPath;//"Resources\\pushCerUse.p12";
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\":\"" + apnsMessage + "\",\"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;
} }

.net C# 苹果消息推送 工具类的更多相关文章

  1. .NET向APNS苹果消息推送通知

    一.Apns简介: Apns是苹果推送通知服务. 二.原理: APNs会对用户进行物理连接认证,和设备令牌认证(简言之就是苹果的服务器检查设备里的证书以确定其为苹果设备):然后,将服务器的信息接收并且 ...

  2. PHP 苹果消息推送

    /* * 苹果消息推送方法 * $deviceToken 苹果设备token * $message 消息内容 */ function iosmsg_send($deviceToken,$message ...

  3. (转)苹果消息推送服务器 php 证书生成

    1.准备好 aps_developer_identity.cer , push.p12这两个证书文件 2. 生成证书如下: openssl x509 -in aps_developer_identit ...

  4. IOS - 消息推送原理和实现

    一.消息推送原理: 在实现消息推送之前先提及几个于推送相关概念,如下图1-1: 1.Provider:就是为指定IOS设备应用程序提供Push的服务器,(如果IOS设备的应用程序是客户端的话,那么Pr ...

  5. IOS开发之实现App消息推送

    转自:http://blog.csdn.net/shenjie12345678/article/details/41120637 第一部分 首先第一步当然是介绍一下苹果的推送机制(APNS)咯(ps: ...

  6. IOS开发之实现App消息推送(最新)

    好久没有写过博客啦,今天就由本菜鸟给大家做一个简单的IOSApp消息推送教程吧!一切从0开始,包括XCode6, IOS8, 以及苹果开发者中心最新如何注册应用,申请证书以及下载配置概要文件,相信很多 ...

  7. iOS 消息推送原理及实现Demo

    一.消息推送原理: 在实现消息推送之前先提及几个于推送相关概念,如下图1-1: 1.Provider:就是为指定IOS设备应用程序提供Push的服务器,(如果IOS设备的应用程序是客户端的话,那么Pr ...

  8. IOS8开发之实现App消息推送

    第一部分 Apple Push Notification Service 首先第一步当然是介绍一下苹果的推送机制(APNS)咯(ps:其实每一篇教程都有),先来看一张苹果官方对其推送做出解释的概要图. ...

  9. iOS 消息推送原理

    一.消息推送原理: 在实现消息推送之前先提及几个于推送相关概念,如下图: 1. Provider:就是为指定IOS设备应用程序提供Push的服务器,(如果IOS设备的应用程序是客户端的话,那么Prov ...

随机推荐

  1. 数据访问模式之Repository模式

    数据访问模式之Repository模式   数据访问层无非就是对数据进行增删改查,其中增.删.改等我们可以抽象出来写一个公共的接口或抽象类来定义这些方法,并采用一个基类实现这些方法,这样该基类派生的子 ...

  2. JavaScript 实现文本编辑器

    JavaScript 实现文本编辑器 最近,我需要做一个非常基本的网页内容编辑功能.我不想使用 iframe ,我也不想要一个功能特别多的复杂编辑器,只需要很基本的内容编辑功能,例如粗体,斜体,列表, ...

  3. BizTalk 2010/2013 EDI B2B

    BizTalk 2010/2013 EDI B2B项目实践(1)   BizTalk 2010/2013 EDI B2B项目实践(1) BizTalk开发标准EDI B2B是件非常容易的事情,但对于初 ...

  4. Go语言Web框架gwk介绍2

    Go语言Web框架gwk介绍 (二) HttpResult 凡是实现了HttpResult接口的对象,都可以作为gwk返回Web客户端的内容.HttpResult接口定义非常简单,只有一个方法: ty ...

  5. Android 短信模块分析(四) MMS之短信的发送与接收

     MMS之短信的发送与接收分析: 一.信息发送: com.android.mms.data.WorkingMessage.java 类 send()函数: public void send() { . ...

  6. Python2 中文编码处理

    今天写了几个脚本,都遇到了中英文混编的情况.需求要将其中的中文标点符号切换为英文符号. 举个例子: tags = '你好,good, 国语' 要将其中的中文半角逗号替换为英文逗号,为了方便后续的处理 ...

  7. android 常用资料

    网上收集保存的一些常用的android资料,写得都比较不错,和大家分享下,共同学习: _ android ListView美化.docx androidshape.docx android_textv ...

  8. 用Bottle开发web程序(二)

    返回码 在开发web程序时,除了一些服务器错误等,常常需要自定义返回码,以便告诉用户处理请求的结果或者状态.bottle支持自定义的返回码,可以通过以下几种方式进行实现. abort 在bottle中 ...

  9. 深入Java虚拟机:JVM中的Stack和Heap

    在JVM中,内存分为两个部分,Stack(栈)和Heap(堆),这里,我们从JVM的内存管理原理的角度来认识Stack和Heap,并通过这些原理认清Java中静态方法和静态属性的问题. 一般,JVM的 ...

  10. 当我们在谈论kmeans(5)

    本系列意在长期连载分享,内容上可能也会有所删改: 因此如果转载,请务必保留源地址,非常感谢! 博客园:http://www.cnblogs.com/data-miner/(暂时公式显示有问题) 其他: ...