MQTT - java simple test (2)

package bsit.mqtt.demo.one_way;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
/**
 *
 * Title:Server
 * Description: The server pushes topics to multiple clients, that is, different clients can subscribe to the same topic to the server
 * @author chenrl
 * January 6, 2016 at 3:29:28 pm
 */
public class Server {

    public static final String HOST = "tcp://192.168.1.3:61613";
    public static final String TOPIC = "toclient/124";
    public static final String TOPIC125 = "toclient/125";
    private static final String clientid = "server";

    private MqttClient client;
    private MqttTopic topic;
    private MqttTopic topic125;
    private String userName = "admin";
    private String passWord = "password";

    private MqttMessage message;

    public Server() throws MqttException {
        // MemoryPersistence sets the save form of clientid, the default is to save in memory
        client = new MqttClient(HOST, clientid, new MemoryPersistence());
        connect();
    }

    private void connect() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        // set timeout
        options.setConnectionTimeout(10);
        // Set the session heartbeat time
        options.setKeepAliveInterval(20);
        try {
            client.setCallback(new PushCallback());
            client.connect(options);
            topic = client.getTopic(TOPIC);
            topic125 = client.getTopic(TOPIC125);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }

    public void publish(MqttTopic topic , MqttMessage message) throws MqttPersistenceException,
            MqttException {
        MqttDeliveryToken token = topic.publish(message);
        token.waitForCompletion();
        System.out.println("message is published completely! "
                + token.isComplete());
    }

    public static void main(String[] args) throws MqttException {
        Server server = new Server();

        server.message = new MqttMessage();
        server.message.setQos(2);
        server.message.setRetained(true);
        server.message.setPayload("Message pushed to client 124".getBytes());
        server.publish(server.topic , server.message);
        
        server.message = new MqttMessage();
        server.message.setQos(2);
        server.message.setRetained(true);
        server.message.setPayload("Information pushed to client 125".getBytes());
        server.publish(server.topic125 , server.message);

        System.out.println(server.message.isRetained() + "------ratained状态");
    }
}

Client code:
package bsit.mqtt.demo.one_way;  
  
import java.util.concurrent.Executors;  
import java.util.concurrent.ScheduledExecutorService;  
import java.util.concurrent.TimeUnit;  

import org.eclipse.paho.client.mqttv3.MqttClient;  
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;  
import org.eclipse.paho.client.mqttv3.MqttException;  
import org.eclipse.paho.client.mqttv3.MqttSecurityException;  
import org.eclipse.paho.client.mqttv3.MqttTopic;  
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
  
public class Client {  
  
    public static final String HOST = "tcp://192.168.1.3:61613";  
    public static final String TOPIC = "toclient/124";  
    private static final String clientid = "client124";  
    private MqttClient client;  
    private MqttConnectOptions options;  
    private String userName = "admin";
    private String passWord = "password";
  
    private ScheduledExecutorService scheduler;  
  
    private void start() {  
        try {  
            // host is the host name, clientid is the ID of the client connecting to MQTT, which is generally represented by a unique identifier. MemoryPersistence sets the storage form of clientid, which is stored in memory by default.  
            client = new MqttClient(HOST, clientid, new MemoryPersistence());  
            // MQTT connection settings  
            options = new MqttConnectOptions();  
            // Set whether to clear the session, if it is set to false here, it means that the server will keep the connection record of the client, and if it is set to true here, it means that every time you connect to the server, you will connect with a new identity  
            options.setCleanSession(true);  
            // Set the username to connect to  
            options.setUserName(userName);  
            // set the connection password  
            options.setPassword(passWord.toCharArray());  
            // Set the timeout unit to seconds  
            options.setConnectionTimeout(10);  
            // Set the session heartbeat time unit to seconds The server will send a message to the client every 1.5*20 seconds to determine whether the client is online, but this method does not have a reconnection mechanism  
            options.setKeepAliveInterval(20);  
            // set callback  
            client.setCallback(new PushCallback());  
            MqttTopic topic = client.getTopic(TOPIC);  
            //setWill method, which can be called if the project needs to know whether the client is offline. Set the notification message for the final port    
            options.setWill(topic, "close".getBytes(), 2, true);  
              
            client.connect(options);  
            //Subscribe message  
            int[] Qos  = {1};  
            String[] topic1 = {TOPIC};  
            client.subscribe(topic1, Qos);  
            
        } catch (Exception e) {  
            e.printStackTrace ();  
        }  
    }  
   
    public static void main(String[] args) throws MqttException {     
        Client client = new Client();  
        client.start();  
    }  
}

MQTT subscription callback class:
package bsit.mqtt.demo.one_way;  
  
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;  
import org.eclipse.paho.client.mqttv3.MqttMessage;  
  
/**  
 * Callback class for publishing messages  
 *   
 * Must implement the interface of MqttCallback and implement the corresponding interface method. The CallBack class will implement MqttCallBack.  
 * Each client ID requires a callback instance. In this example, the constructor passes the client ID to save as instance data.
 * In a callback, use it to identify which instance of the callback has been started.  
 * Three methods must be implemented in the callback class:  
 *   
 * public void messageArrived(MqttTopic topic, MqttMessage message) to receive subscribed publications.  
 *   
 * public void connectionLost(Throwable cause) is called when the connection is disconnected.  
 *   
 *  public void deliveryComplete(MqttDeliveryToken token))  
 * Called when a delivery token for an already published QoS 1 or QoS 2 message is received.  
 * This callback is activated by MqttClient.connect.  
 *   
 */    
public class PushCallback implements MqttCallback {  
  
    public void connectionLost(Throwable cause) {  
        // After the connection is lost, it is generally reconnected here  
        System.out.println("The connection is disconnected, you can reconnect");  
    }  
    
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());  
    }

    public void messageArrived(String topic, MqttMessage message) throws Exception {
        // The message obtained after subscribe will be executed here  
        System.out.println("Receive message topic: " + topic);  
        System.out.println("Receive message Qos: " + message.getQos());  
        System.out.println("Receive message content: " + new String(message.getPayload()));  
    }  
}


Run the server code, you can see that the server will push a message to the client 124/125 each,
[img]
http://images2015.cnblogs.com/blog/716716/201601/716716-20160107134347700-170220131.png
[/img ] ]

When running the 124 client code, you can see the information received by the 124 client:
[img]
http://images2015.cnblogs.com/blog/716716/201601/716716-20160107134651590-657008026.png
[/img]

Then put Change the Topic of the client code to TOPIC = "toclient/125";clientid = "client125"; and then run the code, you can see the information received by the 125 client
[img]
http://images2015.cnblogs.com/blog /716716/201601/716716-20160107134939684-385092078.png
[/img]

Multiple clients subscribe to the same topic, their clientid must be different. The client 124/125 subscribes to the content of the respective topics, but starts at different times, and receives their respective information after starting, which reflects the push function of the server. Similarly, the sent topic information can be seen in the server's topic, and the access path is: http://127.0.0.1:61680/

In fact, if the server and the client communicate with each other, that is, the client can subscribe and publish, and the server can subscribe and publish, there is no need to distinguish between the server and the client, and the codes on both sides are almost the same. Similarly, two clients are subscribing to the same topic. At this time, the third client publishes the request for this topic. The first two clients can also accept the content of the topic. At this time, the codes of the three clients are almost the same. It's just that the first two are subscriptions and the latter is publishing.

The above is what I learned from my own pure learning. There may be many bugs. I hope that people will criticize and correct it later.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326126635&siteId=291194637