PushSharp的使用

最近做公司的一个项目.一旦数据库插入新的消息,就要通知服务器,将这些新的消息推送给苹果客户端,以前我们的项目中有人做过这个功能,无奈做的有点复杂,而且代码没注释,我压根就没看懂.所以自己打算重新搞一个.

小小研究了一个,找到PushSharp这个类库,(超级强大),然后用了下感觉很不错,推荐给大家,为大家介绍下.

一.首先来了解下这几个类库

引用PushSharp 的几个类库
PushSharp.Core:核心库必须引用
PushSharp.Apple:向苹果推送的类库
PushSharp.Android:C2DM及GCM,用于Android设备
PushSharp.Windows:用于Windows 8
PushSharp.WindowsPhone:用于WP设备
PushSharp.Amazon.Adm:用于Amazon的设备
PushSharp.Blackberry:用于黑莓设备
PushSharp.Google.Chrome:用于Chrome
这些类库按照自己的项目要求使用即可

二.简单的示例代码

注意,如果你需要给苹果推送 你首先要给你的APP去注册一个证书,然后在你的APP中写一些代码,来接受推送.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//创建一个推送对象
 private PushBroker push=new PushBroker();
//关联推送状态事件
push.OnNotificationSent += NotificationSent;
push.OnChannelException += ChannelException;
push.OnServiceException += ServiceException;
push.OnNotificationFailed += NotificationFailed;
push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
push.OnChannelCreated += ChannelCreated;
push.OnChannelDestroyed += ChannelDestroyed;
 
var appleCert = File.ReadAllBytes("证书路径");//将证书流式读取
push.RegisterAppleService(new ApplePushChannelSettings(appleCert, "证书密码"));//注册推送通道
push.QueueNotification(new AppleNotification()
                                              .ForDeviceToken(messageList[i].DeviceToken)//手机token
                                              .WithAlert(messageList[i].Message)//推送消息内容
                          .WithBadge(7)//设备图标显示的未读数(图标右上角的小标志)
                                              .WithSound("sound.caf"));//提示声音
 
 
push.StopAllServices()//停止推送服务.
 
  #region=====推送状态事件
 
        static void DeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, INotification notification)
        {
            //Currently this event will only ever happen for Android GCM
            //Console.WriteLine("Device Registration Changed:  Old-> " + oldSubscriptionId + "  New-> " + newSubscriptionId + " -> " + notification);
        }
        // 推送成功
        static void NotificationSent(object sender, INotification notification)
        {
             
        }
        // 推送失败
        static void NotificationFailed(object sender, INotification notification, Exception notificationFailureException)
        {
            //Console.WriteLine("Failure: " + sender + " -> " + notificationFailureException.Message + " -> " + notification);
        }
 
        static void ChannelException(object sender, IPushChannel channel, Exception exception)
        {
            //Console.WriteLine("Channel Exception: " + sender + " -> " + exception);
        }
 
        static void ServiceException(object sender, Exception exception)
        {
            //Console.WriteLine("Channel Exception: " + sender + " -> " + exception);
        }
 
        static void DeviceSubscriptionExpired(object sender, string expiredDeviceSubscriptionId, DateTime timestamp, INotification notification)
        {
            //Console.WriteLine("Device Subscription Expired: " + sender + " -> " + expiredDeviceSubscriptionId);
        }
 
        static void ChannelDestroyed(object sender)
        {
            //Console.WriteLine("Channel Destroyed for: " + sender);
        }
 
        static void ChannelCreated(object sender, IPushChannel pushChannel)
        {
            //Console.WriteLine("Channel Created for: " + sender);
        }
        #endregion

三.解决多信息推送,并且推送到不同的设备上.我写了一个类,来做这些事.现在也给大家看看

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PushSharp.Apple;
using PushSharp.Core;
using PushSharp;
using System.IO;
using CYPInformationSystem.Model;
using System.Threading;
namespace CYPInformationSystem.PushMessage
{
    /// <summary>
    /// 描述:苹果客户端推送类
    /// 作者:茹化肖
    /// 时间:2014年7月4日16:19:40
    /// </summary>
    public class ApplePushService
    {
        private static ApplePushService applePushService;
        private static readonly object syncObject = new object();
        private PushBroker push;//创建一个推送对象
        private List<MessageModel> messageList;//消息实体队列
        private readonly string appleCertpath = AppDomain.CurrentDomain.BaseDirectory +ConfigurationManager.AppSettings["appleCertpath"];
        private readonly string appleCertPwd = ConfigurationManager.AppSettings["appleCertPwd"];//密码
        private ApplePushService()
        {
            //确保该对象被实例化
            this.push = new PushBroker();
            this.messageList = new List<MessageModel>();
            //关联推送状态事件
            push.OnNotificationSent += NotificationSent;
            push.OnChannelException += ChannelException;
            push.OnServiceException += ServiceException;
            push.OnNotificationFailed += NotificationFailed;
            push.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
            push.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
            push.OnChannelCreated += ChannelCreated;
            push.OnChannelDestroyed += ChannelDestroyed;
             
        }
        #region=====公布给外接调用的方法
        /// <summary>
        /// 获取对象实例
        /// </summary>
        /// <returns></returns>
        public static ApplePushService GetInstance()
        {
            if (applePushService == null)
            {
                lock (syncObject)
                {
                    if (applePushService == null)
                    {
                        applePushService = new ApplePushService();
                        applePushService.TherdStart();
                    }
                }
            }
            return applePushService;
        }
        /// <summary>
        /// 添加需要推送的消息
        /// </summary>
        /// <param name="message">消息体</param>
        public void AddMessage(MessageModel message)
        {
            messageList.Add(message);
             
        }
        /// <summary>
        /// 推送消息
        /// </summary>
        /// <param name="msg">消息体</param>
        /// <param name="token">用户token</param>
        private void SendMessage()
        {
            try
            {
                var appleCert = File.ReadAllBytes(appleCertpath);
                if (appleCert.Length > 0 && appleCert != null)//证书对象不为空
                {
                    push.RegisterAppleService(new ApplePushChannelSettings(appleCert, appleCertPwd));
                    while (true)
                    {
                        if (messageList.Count > 0)//如果 消息队列中的消息不为零 推送
                        {
                            for (int i = 0; i < messageList.Count; i++)
                            {
                                push.QueueNotification(new AppleNotification()
                                                      .ForDeviceToken(messageList[i].DeviceToken)
                                                      .WithAlert(messageList[i].Message).WithBadge(7)
                                                      .WithSound("sound.caf"));
                            }
                            messageList.Clear();//推送成功,清除队列
                        }
                        else
                        {
                            //队列中没有需要推送的消息,线程休眠5秒
                            Thread.Sleep(5000);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 启动推送
        /// </summary>
        private void TherdStart()
        {
            Thread td = new Thread(SendMessage);
            td.IsBackground = true;
            td.Start();
        }
        #endregion
 
 
        #region=====推送状态事件
 
        static void DeviceSubscriptionChanged(object sender, string oldSubscriptionId, string newSubscriptionId, INotification notification)
        {
            //Currently this event will only ever happen for Android GCM
            //Console.WriteLine("Device Registration Changed:  Old-> " + oldSubscriptionId + "  New-> " + newSubscriptionId + " -> " + notification);
        }
        /// <summary>
        /// 推送成功
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="notification"></param>
        static void NotificationSent(object sender, INotification notification)
        {
             
        }
        /// <summary>
        /// 推送失败
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="notification"></param>
        /// <param name="notificationFailureException"></param>
        static void NotificationFailed(object sender, INotification notification, Exception notificationFailureException)
        {
            //Console.WriteLine("Failure: " + sender + " -> " + notificationFailureException.Message + " -> " + notification);
        }
 
        static void ChannelException(object sender, IPushChannel channel, Exception exception)
        {
            //Console.WriteLine("Channel Exception: " + sender + " -> " + exception);
        }
 
        static void ServiceException(object sender, Exception exception)
        {
            //Console.WriteLine("Channel Exception: " + sender + " -> " + exception);
        }
 
        static void DeviceSubscriptionExpired(object sender, string expiredDeviceSubscriptionId, DateTime timestamp, INotification notification)
        {
            //Console.WriteLine("Device Subscription Expired: " + sender + " -> " + expiredDeviceSubscriptionId);
        }
 
        static void ChannelDestroyed(object sender)
        {
            //Console.WriteLine("Channel Destroyed for: " + sender);
        }
 
        static void ChannelCreated(object sender, IPushChannel pushChannel)
        {
            //Console.WriteLine("Channel Created for: " + sender);
        }
        #endregion
    }
}

这里用单例来保证,整个应用程序中只会有这一个推送对象,只有一个管道来推送.

不然的话 你多次来注册这个管道会报错的.

还遇到过 一个问题,.Newtonsoft.Json 这个程序集有时候报错,说版本不对. 这个程序集是类序列化消息的.

我的解决办法是,去获取PushSharp 的源码.官方网站:https://github.com/Redth/PushSharp

然后自己编译一下,将生成的Dll文件 拿过来 引用到你的项目中.就可以使用了 ,至于其他问题 和别的平台没有去测试

 
 
分类: 心得
 

PushSharp的使用的更多相关文章

  1. 使用PushSharp给iOS应用推送消息

    PushSharp是一个C#编写的服务端类库,用于推送消息到各种客户端,支持iOS(iPhone/iPad).Android.Windows Phone.Windows 8.Amazo.Blackbe ...

  2. 使用PushSharp进行IOS发布应用的消息推送

    在做.NET向IOS设备的App进行消息推送时候,采用的是PushSharp开源类库进行消息的推送,而在开发过程中,采用的是测试版本的app,使用的是测试的p12证书采用的是ApnsConfigura ...

  3. IOS通过PushSharp开源框架发送推送

    1,首先生成推送证书: openssl x509 -in aps_developer_identity.cer -inform DER -out aps_developer_identity.pem ...

  4. 【苹果通知APNs】不知道大家用过PushSharp没?

    好久没写东西了,近期在研究Jenkins,大家有兴趣可以一起来玩玩交流,学习DevOps还是蛮重要. 近期我负责的项目里需要APNs的通知,这个自己单独开发还是蛮费功夫,故用了第三方开源的PushSh ...

  5. iOS开发资源:推送通知相关开源项目--PushSharp、APNS-PHP以及Pyapns等

    PushSharp  (github) PushSharp是一个实现了由服务器端向移动客户端推送消息的开源C#库,支持 iOS (iPhone/iPad APNS). Android (C2DM/GC ...

  6. PushSharp 由于远程方已关闭传输流,身份验证失败。

    前段时间用到了PushSharp给APNS发推送,但是用的时候遇见很诡异的事情,每次第一次运行的时候能成功发送到 但是接下来就无限的提示“由于远程方已关闭传输流,身份验证失败. “ 然后我就各种找原因 ...

  7. iOS开发系列--通知与消息机制

    概述 在多数移动应用中任何时候都只能有一个应用程序处于活跃状态,如果其他应用此刻发生了一些用户感兴趣的那么通过通知机制就可以告诉用户此时发生的事情.iOS中通知机制又叫消息机制,其包括两类:一类是本地 ...

  8. 基于.NET平台常用的框架整理(转)

    自从学习.NET以来,优雅的编程风格,极度简单的可扩展性,足够强大开发工具,极小的 学习曲线,让我对这个平台产生了浓厚的兴趣,在工作和学习中也积累了一些开源的组件,就目前想到的先整理于此,如果再想到, ...

  9. DotNet 资源大全中文版(Awesome最新版)

    Awesome系列的.Net资源整理.awesome-dotnet是由quozd发起和维护.内容包括:编译器.压缩.应用框架.应用模板.加密.数据库.反编译.IDE.日志.风格指南等. 算法与数据结构 ...

随机推荐

  1. Web在线视频方案浅谈

    写在前面 最近因为项目预研,花时间和精力了解并总结了现如今web在线视频的一些解决方案,由于资历薄浅,措辞或是表述难免出现遗漏,还望各位海涵,有好的建议或方案还望赐教,定细心学习品位. 如今的web技 ...

  2. linux中fork()函数具体解释(原创!!实例解说)

     一.fork入门知识 一个进程,包含代码.数据和分配给进程的资源.fork()函数通过系统调用创建一个与原来进程差点儿全然同样的进程,也就是两个进程能够做全然同样的事,但假设初始參数或者传入的变量不 ...

  3. 应用ExcelPackage导出Excel

    前阵子工作需要,要实现从数据库中导出数据到Excel.老套路 先去百度上查阅资料,发现了以下几种方法: 1:将DataGrid控件中的数据导出Excel 2:将dataview导出excel 3:从网 ...

  4. ArcGIS for Silverlight 地图卷帘

    原文:ArcGIS for Silverlight 地图卷帘 ArcGIS 地图卷帘 for Silverlight 地图卷帘,其实就是遮罩的效果,在Silverlight里实现这样的效果,对于熟悉S ...

  5. Android重力加速度传感器数据去噪

    public void onSensorChanged(SensorEvent event) { final float alpha = 0.8; gravity[0] = alpha * gravi ...

  6. 集成 Entity Framework

    ABP 基础设施层——集成 Entity Framework 本文翻译自ABP的官方教程<EntityFramework Integration>,地址为:http://aspnetboi ...

  7. Chromium Graphics: GPUclient的原理和实现分析之间的同步机制-Part I

    摘要:Chromium于GPU多个流程架构的同意GPUclient这将是这次访问的同时GPU维修,和GPUclient这之间可能存在数据依赖性.因此必须提供一个同步机制,以确保GPU订购业务.本文讨论 ...

  8. Sql Server之旅——第五站 确实不得不说的DBCC命令

    原文:Sql Server之旅--第五站 确实不得不说的DBCC命令 今天研发中心办年会,晚上就是各自部门聚餐了,我个人喜欢喝干红,在干红中你可以体味到那种酸甜苦辣...人生何尝不是这样呢???正好 ...

  9. Redis实现高并发分布式序列号

    使用Redis实现高并发分布式序列号生成服务 序列号的构成 为建立良好的数据治理方案,作数据掌握.分析.统计.商业智能等用途,业务数据的编码制定通常都会遵循一定的规则,一般来讲,都会有自己的编码规则和 ...

  10. jQuery自定义右键菜单

    首先看下效果,效果在最下面: 代码: body { font-size: 12px; margin: 0px; padding: 0px; } form,div,ul,li { margin: 0px ...