iPhone消息推送机制实现与探讨

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;
        }

}

PS:上面这段代码是从网上找的,做了些小改动。

C# 推送信息到APNs的更多相关文章

  1. ZPush--基于netty4实现的苹果通知推送服务(APNs)Javaclient

    简单说下实现苹果通知推送服务(APNs)client的一些要注意的地方: 使用长连接: sanboxserver是无用的,调试时直接用"gateway.push.apple.com" ...

  2. HTML5 WebSocket 实时推送信息测试demo

    测试一下HTML5的websocket功能,实现了客户端→服务器实时推送信息到客户端,包括推送图片: websocket实现MessageInbound类 onTextMessage()/onBina ...

  3. pushlet实现服务器端向客户端推送信息

    使用Pushlet来实现服务器端向客户端推送信息 1.   实现方式: 有两种实现方式: 1.         通过配置文件来实现定时的从服务器端向客户端推送信息 2.         通过API主动 ...

  4. asp.net 实现微信公众平台的主动推送信息

    通过学习借鉴朋友的实现方法进行整理(微信公众帐号主动发送消息给用户,asp.net版本). /// <summary> /// MD5 32位加密 /// </summary> ...

  5. java 使用 comet4j 主动向客户端推送信息 简单例子

    [背景] 今天,一个前端的师弟问我怎样做实时聊天窗口,我毫不犹豫地说:在前台定时访问服务端呀!师弟默默地百度了一番,最后告诉我,有一种技术是后服务端动推送信息给客户端的,这种技术的名字叫comet,我 ...

  6. 使用Pushlet来实现服务器端向客户端推送信息

        使用Pushlet来实现服务器端向客户端推送信息 1.   实现方式: 有两种实现方式: 1.         通过配置文件来实现定时的从服务器端向客户端推送信息 2.         通过A ...

  7. iOS打包后收不到推送信息

    今天遇到的一个特别神奇的问题: 应用在测试环境下打的包收不到推送了,打包之后都没有推送,但是我真机测试又是可以收到推送消息的.经过好久才找到原因,感觉很坑.这里记录一下问题: 1.由于我的推送第三方使 ...

  8. SpringBoot2.0集成WebSocket,实现后台向前端推送信息

    感谢作者,支持原创: https://blog.csdn.net/moshowgame/article/details/80275084 什么是WebSocket? WebSocket协议是基于TCP ...

  9. Python接入企业微信 - 推送信息到内部群里

    前言 之前一篇文章提到了使用wechatpy库来实现企业微信应用登录:Django + Taro 前后端分离项目实现企业微信登录 其实这个库可以实现的功能非常多,基本微信开发涉及到的功能都能实现. 本 ...

随机推荐

  1. LoadRunner中的参数与变量

    在LoadRunner脚本开发中,经常会遇到参数与变量相互转换的情况,本文对常见的转换情形进行了方法总结. 1.变量的赋值 //将字符串赋值给变量 ]; strcpy(strTemp, "H ...

  2. [App]华为P6设置与Xamarin Studio连通测试

    使用模拟器进行调试十分麻烦,而且速度很慢,手头上有手机一台正好做测试机器,不过一直无法连通电脑. 百度了一番才知道,首先要在连接时候选择: PC 助手(HiSuite) 这样会加载一个类似驱动盘的资源 ...

  3. C#面向对象的三大特征

    一,封装:我们可以把世界上任何一个东西都看作为一个对象,那么我们这里以人为例,一个人就肯定是一个对象了.那么封装是什么呢?封装就是这个人要完成一件事情,他所需要的任何工具都带在了自己的身上,所需要的技 ...

  4. 洛谷1373 小a和uim之大逃离

    洛谷1373 小a和uim之大逃离 本题地址:http://www.luogu.org/problem/show?pid=1373 题目背景 小a和uim来到雨林中探险.突然一阵北风吹来,一片乌云从北 ...

  5. 【解决】Internet访问看似正常(无叹号受限)却打不开网页

    嘛╮(╯▽╰)╭ 可能是前几天中了一等奖败了人品 .. 今天果断受点小挫折 事情是这样的:昨晚电脑在不插电的情况下打了一小时“剑灵”,有点烫,电量剩30%,关机睡觉,今早发现上不去网页了! 桌面右下角 ...

  6. [LeetCode] 234. Palindrome Linked List 解题思路

    Given a singly linked list, determine if it is a palindrome. Follow up:Could you do it in O(n) time ...

  7. 【转】Mac OS X 中 Zsh 下 PATH 环境变量的正确设置

    在 Mac OS X 中使用 zsh,环境变量 PATH 一不小心就会变得很紊乱,表现为自己设置的路径总是被放到系统路径之后,部分路径还会有重复.这是我们不太了解 zsh 启动时加载文件的顺序和 Ma ...

  8. ReactiveCocoa框架学习1

    写block直接使用inline block的声明类型 在ARC中使用strong,如果不使用strong,则会被销毁 在非ARC中使用copy block在开发中的使用场景 把block保存到对象中 ...

  9. VS2013/2012 下无法打开 源 文件“stdafx.h”的解决方法

    VS2013/2012下代码一写上去保存就报错了,下方提示无法打开 源 文件“stdafx.h” 如图: 百度了一下,对于VS2010有这样的方法可以解决: 在项目属性中展开C/C++,选择常规,在附 ...

  10. Java_Web 连接池

    对于共享资源,有一个很著名的设计模式:资源池(Resource Pool).该模式正是为了解决资源的频繁分配﹑释放所造成的问题.为解决我们的问题,可以采用数据库连接池技术.数据库连接池的基本思想就是为 ...