android消息推送GCM、XMPP、MQTT三种方案的优劣,越仔细越好,有具体分析更好!

android消息推送GCM、XMPP、MQTT三种方案的优劣,越仔细越好,有具体分析更好!,第1张

android消息推送GCM、XMPP、MQTT三种方案的优劣:
1、GCM服务(Google Cloud Messaging)优点:Google提供的服务、原生、简单,无需实现和部署服务端。缺点:Android版本限制,该服务在国内不够稳定、需要用户绑定Google帐号,受限于Google。
2、XMPP协议(Openfire + Spark + Smack)优点:协议成熟、强大、可扩展性强、目前主要应用于许多聊天系统中,且已有开源的Java版的开发实例androidpn。缺点:协议较复杂、冗余(基于XML)、费流量、费电,部署硬件成本高。
3、MQTT协议优点:协议简洁、小巧、可扩展性强、省流量、省电,目前已经应用到企业领域,且已有C++版的服务端组件rsmb。缺点:不够成熟、实现较复杂、服务端组件rsmb不开源,部署硬件成本较高。
d消息推送可以去了解一下极光,极光是个不错的平台。极光紧密围绕移动开发者需求,打造的开发者服务平台,可以提供一站式SaaS服务,通过全面覆盖PC、手机、传感器、无线路由器等多种设备数据,打造全域数据平台。当前,不断更新的SaaS产品及服务已深受国内百万开发者的认可和信赖。

MQTT (Message Queuing Telemetry Transport,消息队列遥测传输) 是一种基于 TCP/IP 协议族的应用层协议。MQTT 协议是专门针对硬件性能低下 & 网络状况不稳定的场景设计的,这使得 MQTT 在物联网和移动应用等受限场景得到广泛应用。

目前,MQTT 主要分为两个大版本:

物联网和移动应用场景的特点是硬件性能低下和网络状况不稳定,而 MQTT 协议就是专门针对这种环境设计的,主要在四个方面有优势:

结论:这三种协议并没有绝对的优胜者,最好的协议取决于具体的需求和限制条件。但如果只从带宽、电池、功能多样性这些基本条件看,MQTT 在其中是更占优的选择。

MQTT 协议的设计特性中包含了一项 “高可靠性交付”,它需要一个保证可靠的底层传输层协议,因此 TCP 协议、TLS 协议、WebSocket 协议都可以作为 MQTT 的底层协议。而无连接的 UDP 协议会丢失或重排数据,不能满足 MQTT 协议的传输需要。

MQTT 是基于发布 - 订阅模型 (pub/sub) 的消息传递协议,与请求 - 响应模型不同,发布 - 订阅模型主要有三种角色: publisher & subscriber & subscriber

当 client 发布某个主题的消息时,broker 会将该消息分发给任何已订阅该主题的 client。通常来说,client 不会存储消息,一旦消息被发送到这些 client,消息就会从 broker 上删除。另外,保留消息、持久连接和服务质量 QoS 可能会导致消息临时存储在 broker 上。

发布 - 订阅模式使得 消息的发布者和订阅者解耦 ,主要体现为空间解耦和时间解耦:

引用自 >可以的
MQTT协议是为大量计算能力有限,且工作在低带宽、不可靠的网络的远程传感器和控制设备通讯而设计的协议,国内很多企业都广泛使用MQTT作为Android手机客户端与服务器端推送消息的协议

根据实地观察,单台mqtt服务如果并发达到5w以上,就经常出故障;在2w左右内网访问服务器就比较卡了。
注:配置是4核 16G内存,虚机。配置有点差。对CPU的消耗比较高,内存基本没啥消耗,所以建议把CPU整好点。

MQTT连接建立的代码(SSL方式)
[java] view plain copy
public static void connect(Driver driver) {
ServerConfig serverConfig = UserModuleInstancegetServerConfig();
MqttConnectOptions conOpt = new MqttConnectOptions();
try {
SSLContext sslContext;
KeyStore ts = KeyStoregetInstance("BKS");
tsload(contextgetResources()openRawResource(Rrawtest_cert),
"123456"toCharArray());
TrustManagerFactory tmf = TrustManagerFactorygetInstance("X509");
tmfinit(ts);
TrustManager[] tm = tmfgetTrustManagers();
sslContext = SSLContextgetInstance("TLS");
sslContextinit(null, tm, null);

SocketFactory factory = sslContextgetSocketFactory();
conOptsetSocketFactory(factory);
} catch (Exception e) {
eprintStackTrace();
}
<span style="white-space:pre"> </span>
[java] view plain copy
<span style="white-space:pre"> </span>//paho库得
Iterator<MapEntry<String, Connection>> it = Connections
getInstance(context)getConnections()entrySet()iterator();
while (ithasNext()) {
MqttClientAndroidService detectClient = itnext()getValue()
getClient();
try {
detectClientdisconnect();
} catch (MqttException e) {
eprintStackTrace();
}
itremove();
}

// The basic client information
MqttClientAndroidService client;
client = ConnectionsgetInstance(context)createClient(context,
serverConfiggetUri(), serverConfigclientId);
Integer qos = IntegerparseInt(contextgetResources()getString(
Rstringqos));
Boolean retained = BooleanparseBoolean(contextgetResources()
getString(Rstringretained));

// connection options
int timeout = IntegerparseInt(contextgetResources()getString(
(Rstringtimeout)));
int keepalive = IntegerparseInt(contextgetResources()getString(
Rstringkeepalive));

Connection connection = new Connection(serverConfiggetClientHandle(),
serverConfigclientId, serverConfigserver,
IntegerparseInt(serverConfigport), context, client,
serverConfigssl);

// connectionregisterChangeListener(changeListener);
// connect client

String[] actionArgs = new String[1];
actionArgs[0] = serverConfigclientId;
connectionchangeConnectionStatus(ConnectionStatusCONNECTING);

boolean cleanSession = false;
conOptsetCleanSession(cleanSession);
conOptsetConnectionTimeout(timeout);
conOptsetKeepAliveInterval(keepalive);
if (!TextUtilsisEmpty(serverConfiguser)) {
conOptsetUserName(serverConfiguser);
}
if (!TextUtilsisEmpty(serverConfigpwd)) {
conOptsetPassword(serverConfigpwdtoCharArray());
}
// conOptsetPassword("1111"toCharArray());
final ActionListener callback = new ActionListener(context,
ActionListenerActionCONNECT, drivergetMqttUtilsCallback(),
serverConfiggetClientHandle(), actionArgs);

boolean doConnect = true;

String message = ActivityConstantsmessage;
String topic = ActivityConstantstopic;

if ((!TextUtilsisEmpty(message) || !TextUtilsisEmpty(topic))) {
// need to make a message since last will is set
try {
conOptsetWill(topic, messagegetBytes(), qosintValue(),
retainedbooleanValue());
} catch (Exception e) {
eprintStackTrace();
doConnect = false;
callbackonFailure(null, e);
}
}
clientsetCallback(new MqttCallbackHandler(context, serverConfig
getClientHandle(), driver));

connectionaddConnectionOptions(conOpt);
ConnectionsgetInstance(context)addConnection(connection);
if (doConnect) {
try {
clientconnect(conOpt, null, callback);
} catch (MqttException e) {
Loge(TAG, "MqttException Occured", e);
}
}
}
发布(publish)代码
[java] view plain copy
public static void publish(String clientHandle, String topic,
JSONObject jsonObj, int qos) {
MqttClientAndroidService client = ConnectionsgetInstance(context)
getConnection(clientHandle)getClient();
if (!isConnected(context)) {
try {
clientconnect();
} catch (MqttException e) {
eprintStackTrace();
}
ToastmakeText(context, "please try again", ToastLENGTH_SHORT)
show();
return;
}
if (topic == null) {
ToastmakeText(context, "can not get other's identity for now",
ToastLENGTH_SHORT)show();
return;
}
String[] args = new String[2];
if (jsonObjoptLong("time") != 0) {
args[0] = StringvalueOf(jsonObjoptLong("time"));
args[1] = topic;
}

Boolean retained = BooleanparseBoolean(contextgetResources()
getString(Rstringretained));
try {
clientpublish(topic, jsonObjtoString()getBytes(), qos, retained,
null, new ActionListener(context, ActionPUBLISH, null,
clientHandle, args));
} catch (MqttSecurityException e) {
Loge(TAG,
"Failed to publish a messged from the client with the handle "
+ clientHandle, e);
} catch (MqttException e) {
Loge(TAG,
"Failed to publish a messged from the client with the handle "
+ clientHandle, e);
}
}
订阅(subscribe)代码
[java] view plain copy
public static void subscribe(MqttUtilsCallback mqttUtilsCallback,
String clientHandle, String topic) {
MqttClientAndroidService client = ConnectionsgetInstance(context)
getConnection(clientHandle)getClient();
if (client == null || (client != null && !clientisConnected())) {
ToastmakeText(context, "please connect to server first",
ToastLENGTH_SHORT)show();
return;
}

if (TextUtilsisEmpty(topic)) {
topic = "hello";
}
String[] topics = new String[1];
topics[0] = topic;
try {
clientsubscribe(topic, 1, null, new ActionListener(context,
ActionListenerActionSUBSCRIBE, mqttUtilsCallback,
clientHandle, topics));
} catch (MqttSecurityException e) {
Loge(TAG, "Failed to subscribe to" + topic
+ " the client with the handle " + clientHandle, e);
} catch (MqttException e) {
Loge(TAG, "Failed to subscribe to" + topic
+ " the client with the handle " + clientHandle, e);
}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zz/13457916.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-08-10
下一篇 2023-08-10

发表评论

登录后才能评论

评论列表(0条)

保存