注:客户端代码实现请看我的上一篇
1mqtt发送消息
发送时不用多讲,每次发送肯定需要运行一次发送消息方法
MyMqttClient mqttClient = new MyMqttClient();
@org.junit.Test
public void testMqtt1() throws InterruptedException, MqttException {
final long timeInterval = 5000;
while(true) {
Thread.sleep(timeInterval);
mqttClient.publishMessage("world/1234", "hello", 1);
System.out.println("qqq");
}
}
2mqtt接收消息
接收消息只需要运行一次receive()方法即可,但需要保证的是方法进程不可以停止,具体可以用tomcat启动线程或者自己写一个循环阻塞等,只要本方法不停就可以一直接收订阅的消息,比如:
@org.junit.Test
public void testMqtt1() throws InterruptedException, MqttException {
final long timeInterval = 5000;
myMqttRecieveMessage.receive(myMqttRecieveMessage.client, "world");
while(true) {
Thread.sleep(timeInterval);
}
}