mqtt协议详解二 token什么意思

于 ,14:57&&
归类于:, &&Tags: .
iOS消息推送直接使用苹果消息推送协议,服务器端采用easy apns:
Android消息推送采用MQTT协议,服务器端采用mosquito+PhpMQTTClient
mosquito:
PhpMQTTClient
iOS消息推送
1.0 、消息推送证书生成
在apple官网分别生成消息推送的development和production证书,这里只使用development证书,假定为push.p12
1.1、生成easy apns所需要的pem格式的证书
openssl pkcs12 -clcerts -nokeys -out cert.pem -in push.p12
openssl pkcs12 -nocerts -out key.pem -in push.p12
openssl rsa -in key.pem -out key.unencrypted.pem
cat cert.pem key.unencrypted.pem & apns-dev-cert.pem
对production证书重复以上类似步骤,生成apns-cert.pem
1.2、easy apns安装配置
由于easy apns使用了mysqli来连接mysql,因此记得在安装php时候在php.ini启用mysqli
1.2.1、 easy apns下载
从 /manifestinteractive/easyapns
下载easy apns代码
unzip manifestinteractive-easyapns-6f5731a.zip
1.2.2、easy apns数据库初始化
创建数据库apns
用manifestinteractive-easyapns-6f5731a/manifestinteractive-easyapns-6f5731a/src/sql/apns.sql建立所需要的数据库表
1.2.3、easy apns php应用
将manifestinteractive-easyapns-6f5731a/manifestinteractive-easyapns-6f5731a/src/php下的代码拷贝到服务器对应的目录下,假设为/var/www/html/apns
将1.1生成的apns-dev-cert.pem 和apns-cert.pem 拷贝到/var/www/html/apns下
修改classes/class_APNS.php如下参数:
private $logPath = ‘/var/www/html/apns/apns.log';
private $certificate = ‘/var/www/html/apns/apns-cert.pem';
private $sandboxCertificate = ‘/var/www/html/apns/apns-dev-cert.pem'; // change this to your development certificate absolute path
将证书权限修改为644
修改apns.php如下参数
$db = new DbConnect(‘localhost’, ‘apnsuser’, ‘apnspassword’, ‘apnsdb’);
将localhost、apnsuser、apnspassword、apnsdb改成对应的参数
1.2.4、crontab配置
* * * * * nice /usr/bin/php -f /var/www/html/apns/apns.php fetch & /var/www/html/apns/apns.log 2&&1 &
1.2.5、测试
在manifestinteractive-easyapns-6f5731a/manifestinteractive-easyapns-6f5731a/src/delegate/Delegate.m基础上,建立iPhone测试Demo程序
修改Delegate.m中的:
NSString *host = @”“;
//修改为指向实际消息推送的Web服务器的地址和端口
NSString *urlString = [NSString stringWithFormat:@”/apns.php?task=%@&appname=%@&appversion=%@&deviceuid=%@&devicetoken=%@&devicename=%@&devicemodel=%@&deviceversion=%@&pushbadge=%@&pushalert=%@&pushsound=%@”, @”register”, appName,appVersion, deviceUuid, deviceToken, deviceName, deviceModel, deviceSystemVersion, pushBadge, pushAlert, pushSound];
将/apns.php? 修改为easy apns实际的url访问路径,此处为:/apns/apns.php
修改samples.php
$db = new DbConnect(‘localhost’, ‘apnsuser’, ‘apnspassword’, ‘apnsdb’);
将localhost、apnsuser、apnspassword、apnsdb改成对应的参数
在iPhone上运行Demo程序,查看服务器数据库apns_devices表,看Demo程序是否成功注册
如果在apns_devices表中已有iPhone客户端的设备信息,则修改对应的development字段为:sandbox
运行发送消息的例子:
a、如果要向所有已注册的设备推送消息,可以将samples.php中的例子修改为
$apns-&newMessage(NULL);
$apns-&addMessageAlert(‘所有设备推送测试消息’);
$apns-&addMessageCustom(‘acme2′, array(‘bang’, ‘whiz’));
$apns-&queueMessage();
b、如果要支持推送表情消息,可以参考:
c、查看classes/class_APNS.php的_fetchMessages()可知,easy apns缺省每次只处理100条记录,为提高发送效率,可适当提高此参数
1.2.6、其他问题
a、消息大批量发送问题
目前由于APNS(Apple Push Notification Service)机制原因,目前easy apns的消息发送机制为:
对每一条发送的消息,为所有需要推送的设备都在数据库中apns_messages创建一条消息,然后通过轮训数据库表来一条一条向苹果消息推送服务器发送消息
在需要推送的设备较多的情况下,由于存在大量的网络链接,导致存在较长时间的延迟。
解决方案:
1、做批量消息推送时候,保持与苹果消息推送服务器的长链接
2、使用批量发送机制
具体可参考:
You should also retain connections with APNs across multiple notifications. APNs may consider connections that are rapidly and repeatedly established and torn down as a denial-of-service attack. Upon error, APNs closes the connection on which the error occurred.
As a provider, you are responsible for the following aspects of push notifications:
You must compose the notification payload (see “The Notification Payload”).
You are responsible for supplying the badge number to be displayed on the application icon.
You should regularly connect with the feedback web server and fetch the current list of those devices that have repeatedly reported failed-delivery attempts. Then you should cease sending notifications to the devices associated with those applications. See “The Feedback Service” for more information.
b、数据库轮询效率问题
由于目前easy apns是采用数据库轮询的方式来进行消息推送,效率并不高,后期可以修改为Redis这样的NOSQL方案
1.3、参考文档:
2、Android消息推送
MQTT服务器采用mosquito
PHP管理包采用phpmqttclient:
2.1、mosquito安装
cd /etc/yum.repos.d
wget http://download.opensuse.org/repositories/home:/oojah:/mqtt/CentOS_CentOS-5/home:oojah:mqtt.repo
yum update
yum install mosquitto
2.2、mosquito命令行使用
mosquito安装主要包含三个部分:
mosquitto mosquitto服务器主程序,实现了MQTT协议
mosquitto_pub mosquitto发布消息的命令行程序
mosquitto_sub mosquitto订阅消息的命令行程序
启动mosquitto在前台运行
启动mosquitto在后台运行
mosquitto -d
启动订阅:
mosquitto_sub -t hello/world //订阅topic为hello/world的消息,使用默认地址和端口1883
mosquitto_pub -t hello/world -m “hello,world” //发布topic 为hello/world的消息 “hello,world”
更多mosquitto命令可以参考
2.3、PhpMQTTClient安装
2.3.1、从/tokudu/PhpMQTTClient 下载
将tokudu-PhpMQTTClient-ba4e494/tokudu-PhpMQTTClient-ba4e494拷贝到服务器对应目录下
假设为/var/www/html/mqtt,可以通过访问phpmqttclient
2.3.2、将index.php的$result = $conn-&connect(SAM_MQTT, array(SAM_HOST =& &#.0.1’, SAM_PORT =& 1883));
$result = $conn-&connect(SAM_MQTT, array(‘SAM_HOST’ =& &#.0.1’, ‘SAM_PORT’ =& 1883));
备注:如果phpmqttclient的http服务器与mosquitto没有安装在同一台服务器,注意将index.php中的127.0.0.1和send_mqtt.php修改成mosquitto的ip地址
2.3.3、将SAM/MQTT/sam_mqtt.php的SAM_PORT和SAM_HOST也都加上”
if ($options[‘SAM_PORT’] == ”) {
$this-&port = 1883;
$this-&port = $options[‘SAM_PORT’];
if ($options[‘SAM_HOST’] == ”) {
$this-&host = ‘localhost';
$this-&host = $options[‘SAM_HOST’];
2.3.4、服务器测试,测试PhpMQTTClient安装成功
启动mosquitto在前台运行,以方便获取连接客户端的信息
在服务器另外一终端上启动订阅消息的进程,订阅所有tokudu开头topic
mosquitto_sub
注意,此处之所以要使用tokudu,可以看index.php的182行
var target = ‘tokudu/’ + $(‘#messageTarget’).val();
在mosquitto的终端获得mosquitto_sub客户端的id
: New client connected from 127.0.0.1 as mosqsub/8491-localhost..
访问 ,push notification target字段填写8491-localhost,push notification text填写需要推送的测试消息
在在mosquitto的终端查看是否收到了推送的消息,如果收到,说明phpmqttclient已经安装配置成功
2.3.5、android Demo程序安装
从 下载Android客户端例子,安装到Android,启动后获取客户端的Device Target
2.3.6、先客户端推送消息
访问 ,push notification target字段填写Android客户端的Device Target,push notification text填写需要推送的测试消息
1、需要在客户端增加向服务器端上报Device Target的通信报文,服务器端获取客户端的设备信息后存入到数据库中。需要发送消息时候从设备信息表中获取Device Target,然后调用推送接口发送消息,可参考send_mqtt.php
2、消息队列的持久化及轮询机制,初期可存放到数据库中(参考easy apns),后期放到NOSQL数据库中。需要程序轮询消息队列,获取mosquitto消息队列状态、对未成功发送的消息重试等
3、大批量消息推送:可能的瓶颈应该主要在mosquitto的处理性能 ,由于是使用C++写的,性能应该可以支撑需要,可以先通过调整mosquitto.conf参数来优化mosquitto的性能。
4、除了MQTT+Mosquitto外,Apache ActiveMQ/Apollo+MQTT也是值得考虑的方案,ActiveMQ 5.6开始也支持MQTT协议了
5、之所以选择MQTT而非XMPP协议,可以参考 ,值得注意的Facebook Messenger也采用了MQTT协议。有空再单独写一篇关于移动终端消息推送整体架构及选型的方案
2.5、参考文档
Technorati 标签: ,,,,
近期评论文章归档
欢迎来到 出家如初,成佛有余.我是 chuanliang....MQTT is a machine-to-machine (M2M)/"Internet of Things" connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. It is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium. For example, it has been used in sensors communicating to a broker via satellite link, over occasional dial-up connections with healthcare providers, and in a range of home automation and small device scenarios. It is also ideal for mobile applications because of its small size, low power usage, minimised data packets, and efficient distribution of information to one or many receivers ()
November 7th, 2014 -
Good news everyone! MQTT v3.1.1 has now become an .
This marks not just the result of 18 months hard work by the Technical Committee, but also the last 15 years of work started by Andy and Arlen. Congratulations to everyone involved.
You can find the standard specification as either
January 22nd, 2014 -
project is rapidly becoming a source of
– currently it contains implementations in C, Java, Javascript, Python (contributed from the mosquitto project), Lua, C++, embedded/minimal C, Go… and an Objective-C client is about to be added. The very popular mosquitto broker recently moved under the Eclipse umbrella too – the
contains both mosquitto, and a fully open-sourced Really Small Message Broker from IBM, which also happens to support MQTT-SN.
, coming up in March, has a strong focus on the Internet of Things.
As part of EclipseCon, the Eclipse Foundation is delighted to host an interoperability testing day for MQTT developers and vendors. The goal is to have representation from a wide range of MQTT brokers, clients, and MQTT-enabled devices. If you work with MQTT, take a look at , and . If you are building APIs or devices on top of MQTT, this is a great way of interacting with the community, broadening awareness of your project or product, and making sure that things work smoothly for you users and customers!
Feel free to , if you have any questions.
January 10th, 2014 -
A significant milestone has been reached in efforts to standardise MQTT. The OASIS MQTT Technical Committee have approved a Committee Specification Draft which is now open for a 30-day public review.
The public review starts 13 January 2014 at 00:00 GMT and ends 11 February 2014 at 23:59 GMT.
This is an open invitation to comment. OASIS solicits feedback from potential users, developers and others, whether OASIS members or not, for the sake of improving the interoperability and quality of its technical work.
More details are available in the .3050人阅读
& & & & 官网英文参考:
Apollo允许客户端通过开放的MQTT协议连接。该协议主要是用在资源有限的驱动上,以及网络不稳定的情况下使用,是一个订阅、发布模型。这种驱动通常不适用类似http,stomp这类基于文本,或者类似openfire,AMQP等传统二进制协议。MQTT是一个简介的二进制协议,适用这类驱动资源受限,而且是不稳定的网络条件下。
之前的稳定发布版本中,MQTT是作为一个Apollo的一个插件提供的。但是现在,这个插件已经变为开发项目的一部分。MQTT在Apollo中已经不需要其他配置文件或者是第三方插件支持了。
MQTT是一个线路层的协议,任何实现该协议的客户端都可以连接到Apollo。当然也可以整合其他MQTT兼容的消息代理中。
更多有关MQTT协议内容,参考
&MQTT协议配置
为了开始使用MQTT协议,首先使用MQTT3.1协议的客户端,连接到Apollo正在监听端口。Apollo会做协议检测,而且自动识别MQTT连接,而且将连接作为MQTT协议处理。你不必要为MQTT协议打开一个端口(STomp,Openfire,AMQP等都是自动识别)。如果你一定指定连接的协议,有下面两种方式:你可以选择不用协议识别,而是为MQTT指定连接:
&connector id=&tcp& bind=&tcp://0.0.0.0:61613& protocol=&mqtt&/&
或者你可以限制哪种协议可以被自动识别。通过下面的&detece&配置方式:
&connector id=&tcp& bind=&tcp://0.0.0.0:61613&&
& &detect protocols=&mqtt openwire& /&
&/connector&
&detect& 下protocols 对应的参数通过空格来隔开支持的通信协议。如果只支持一种协议,就不要空格,默认情况下对任何协议生效。
如果你想调整MQTT默认设置,在apollo.xml文件中有一个&connector& 元素,通过MQTT参数配置:
&connector id=&tcp& bind=&tcp://0.0.0.0:61613&&
& &mqtt max_message_length=&1000& /&
&/connector&
MQTT元素支持下面几个参数:
max_message_length&: The size (in bytes) of the largest message that can be
sent to the broker. Defaults to 100MB(broker能接受的最大消息量:默认是100M)protocol_filters&: A filter which can filter frames being sent/received to
and from a client. It can modify the frame or even drop it.(一个控制发送和接收,Client的过滤器框架。可以修改,删除这个框架)die_delay&: How long after a connection is deemed to be “dead” before the
connec default: 5000ms(在实际断开连接之前,会有默认5000ms的时间被认为连接已经dead)
mqtt 配置元素也可以用来控制目的消息头的解析。下面是支持的参数:
queue_prefix&: a tag used to identi default: null(用来确认目的地类型)path_separator&: used to separate segments i default:&/(用来分割目的地名称)any_child_wildcard&: indicate all child-level destinations that match the
default:&+(识别子目录)any_descendant_wildcard&: indicate destinations that match the
default:#(目标地址通配符)regex_wildcard_start&: pattern used to identify the start of a regex(表示正则表达开始)regex_wildcard_end&: pattern used to identify the end of a regex(表示正则表达结束)part_pattern&: allows you to specify a regex that constrains the naming of
topics. (你可以指定正则表达规则)default:&[ a-zA-Z0-9\_\-\%\~\:\(\)]+
&Client 可用函数库
Apollo 支持MQTT3.1 协议,下面是可用的Clients:
Java :&,&C :&Erlang :&,&.NET :&,&Perl :&, [anyevent-mqtt-perl]/beanz/anyevent-mqtt-perl()Python :&Ruby :&,&Javascript :&Delphi :&Device specific:&,&,&,
如果要找到新支持的Clients ,可以检索:
在目录example 目录下,你可以找到一些例子,实现了与broker之间收发。
&connecting
为了确保broker配置文件的安全,所以只允许一个admin 用户连接,默认的用户名和密码是:admin ,password.
Mqtt 客户端不能specify 虚拟主机(更多请看:see&),以至于默认情况下虚拟主机已经被使用了。通常第一虚拟主机定义在apollo.xml文件中。
&Destination 类型
MQTT协议是订阅,发布协议,是不允许真正的利用队列点对点的消息收发。因此Apollo仅允许利用主题,还进行MQTT消息发送。订阅的概念和持久的主题订阅 和其他协议提到的有些类似,同时也被MQTT CONNECT 框架的clean session属性控制。
&Clean Sessions
但一个Client 发送一个连接,这个连接中clean session 被设置为false,那么之前连接中有相同Client_id 的session 将会被重复使用。这就意味着Client断开了,订阅依然能收到消息。这就等同与同Apollo建立一个长订阅。
如果 clean session 设置为true ,那么新session就开始了,其他的session会慢慢消失,删除。这就是Apollo中定义的普通的主题订阅。
&Topic Retained Messages
如果消息被发布的同时retain 标记被设置,消息将被主题记住,以至于新的订阅到达,最近的retain 消息会被发送到订阅者。比如说:你想发布一个参数,而且你想让最新的这个参数发布到总是可用的订阅了这个主题的客户端上,你就设置在PUBLISH 框架上设置retain 标签。
注意:retained 消息 不会被设置成retained 在 QoS设置为零的broker 重启过程中。
Last Will and Testament Message
当Client第一次连接的时候,有一个will 消息和一个更QoS相关的消息会跟你有关。will消息是一个基础消息,这个基础消息只有在连接异常或者是掉线的时候才会被发送。一般用在你有一个设备,当他们掉了的时候,你需要知道。所以如果一个医疗Client从broker掉线,will消息将会作为一个闹钟主题发送,而且会被系统作为高优先级提醒。
Reliable Messaging
MQTT协议允许Client 发布消息的时候指定Qos参数:
At Most Once (QoS=0)At Least Once (QoS=1)Exactly Once (QoS=2)
这个设置时推送消息给Client,可靠性最低的一种。如果设置Qos=0,那broker就不会返回结果码,告诉你他收到消息了,也不会在失败后尝试重发。这有点像不可靠消息,如JMS。
该设置会确保消息会被至少一次推送到Client。如果推送设置为至少推送一次,Apollo会返回一个回调函数,确保代理已经收到消息,而且确保会确保推送该消息。如果Client 将发布了一个Qos=1的消息,如果在指定的时间内没有收到回复,Client会希望重新发布这个消息。所以可能存在这种情况:代理收到一个需要推送的消息,然后又收到一个消息推送到同一个Client。所以如果传输过程中PUBACK丢失,Client会重新发送,而且不会去检测是否是重发,broker就将消息发送到订阅主题中。
该设置是可靠等级最高的。他会确保发布者不仅仅会推送,而且不会像Qos=1 那样,会被接收两次。当然这个设置会增加网络的负载。当一个消息被发布出去的时候,broker会保存该消息的id,而且会利用任何长连接,坚持要把该消息推送给目标地址。如果Client收到PUBREC 标志,那就表明broker已经收到消息了。 这个时候broker会期待Client发送一个PUBREL 来清除session 中消息id,broker如果发送成功就会发送一个PUBCOMP通知Client。
Wildcard Subscriptions
通配用在主题的目标地址中。这能实现一个主题发送到多个用户,或者多层用户中。
/&is used to separate names in a path(分割路径)+&is used to match any name in a path(通配地址任何字符)#&is used to recursively match path names(递归通配)
比如通配可能这样来用:
PRICE/#&: Any price for any product on any exchange(任何交易中任何产品的价格)PRICE/STOCK/#&: Any price for a stock on any exchange(任何交易中的股票价格)PRICE/STOCK/NASDAQ/+&: Any stock price on NASDAQ(纳斯达克的任何股票价格)PRICE/STOCK/+/IBM&: Any IBM stock price on any exchange(任何交易中IBM股票价格)
Keep Alive
Apollo只有在Client指定了CONNECT的KeepAlive 值的时候,才会设置保持连接、心跳检测。如果one Client指定了keepalive,apollo 将会使用1.5*keepalive值。这个在MQTT中有说明。
Destination Name Restrictions
路径名称限制了使用(a-z, A-Z, 0-9, _, - %, ~, :, ' ', '(', ')' ,. )字符,通配符(*)在复杂的分隔符中。而且确保使用utf-8来编译你的URL。
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:33480次
排名:千里之外
原创:14篇
转载:10篇
译文:18篇
评论:20条
(2)(19)(1)(4)(3)(8)(2)(3)}

我要回帖

更多关于 mqtt协议详解 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信