java与mqtt的那些事(二)

来源:互联网 发布:慈溪行知职高在哪 编辑:程序博客网 时间:2024/06/05 07:10

上回书介绍了java连接mqtt大概的介绍,接下来我们来剖析一下这个MqttClient,废话不多说先进入主题。


MqttClient是实现了IMqttClient这个接口的,然后实现这个接口的方法来完成和Mqtt服务器的交流的,表面上是这样的。其实里面还是有点小玄机的,因为其实MqttClient操作的是MqttAsyncClient。可是为什么要这样来写呢?那说到封装和异步害羞害羞你懂的。好接下里我们详解一下MqttAsyncClient。


好吧具体继承是这样来的:

org.eclipse.paho.client.mqttv3

Class MqttClient

  • java.lang.Object
    • org.eclipse.paho.client.mqttv3.MqttClient
All Implemented Interfaces:
IMqttClient
方法和MqttClient的差不多(因为我也就是扫了一俩眼),那它是怎么完成异步的呢,在MqttAsyncClient这个类中有个类叫ClientComms,这个类是这么介绍的:

/**
 * Handles client communications with the server.  Sends and receives MQTT V3
 * messages.
 */

我们大概来读一下应该是:处理用户与服务器之间的交流,发送和接受MQTT的信息,咦怎么没有异步的信息呢?但是已经很接近真相了在这个私有类叫ConnectBG(竟然没有再API中找到这个类的介绍),OK,OK,OK来看一下ConnectBG的介绍:

// Kick off the connect processing in the background so that it does not block. For instance
 // the socket could take time to create.

翻译(英语不好的我都快把翻译按钮点炸了):开始在后台的连接进程以至于主线程不会被阻塞,这个实例对象需要花费时间去创造(完全觉得是废话鄙视),然后我们去看run方法:其中有一段是这样的:

NetworkModule networkModule = networkModules[networkModuleIndex];
networkModule.start();
receiver = new CommsReceiver(clientComms, clientState, tokenStore, networkModule.getInputStream());
receiver.start("MQTT Rec: "+getClient().getClientId());
sender = new CommsSender(clientComms, clientState, tokenStore, networkModule.getOutputStream());
sender.start("MQTT Snd: "+getClient().getClientId());
callback.start("MQTT Call: "+getClient().getClientId()); 

internalSend(conPacket, conToken);

好吧我也没有一一去细看大眼望去就是接受啊发送啊调用本地方法什么的东东,这样就弄清楚为什么MqttAsyncClient是异步的原因了。

说到连接因为我还没有做好心里准备还是放到下一话吧!!!

原创粉丝点击