上回书介绍了java连接mqtt大概的介绍,接下来我们来剖析一下这个MqttClient,废话不多说先进入主题。
MqttClient是实现了IMqttClient这个接口的,然后实现这个接口的方法来完成和Mqtt服务器的交流的,表面上是这样的。其实里面还是有点小玄机的,因为其实MqttClient操作的是MqttAsyncClient。可是为什么要这样来写呢?那说到封装和异步你懂的。好接下里我们详解一下MqttAsyncClient。
好吧具体继承是这样来的:
Class MqttClient
- java.lang.Object
-
- org.eclipse.paho.client.mqttv3.MqttClient
-
All Implemented Interfaces:
- IMqttClient
/**
* 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是异步的原因了。
说到连接因为我还没有做好心里准备还是放到下一话吧!!!