Using mqtt protocol in java

MQTT: MQTT (Message Queuing Telemetry Transport) is a lightweight communication protocol based on publish/subscribe mode, which is built on TCP/IP protocol and published by IBM in 1999. The biggest advantage of MQTT is that it can provide real-time and reliable messaging services for connecting remote devices with very little code and limited bandwidth. As a low-cost, low-bandwidth instant messaging protocol, it has a wide range of applications in the Internet of Things, small devices, mobile applications and so on.

MQTT is a client-server based message publish/subscribe transfer protocol. MQTT protocol is lightweight, simple, open and easy to implement. These characteristics make it widely applicable. In many cases, including limited environments, such as machine-to-machine (M2M) communications and the Internet of Things (IoT). It has been widely used in satellite link communication sensors, occasional dial-up medical equipment, smart home, and some miniaturized equipment.

Using mqtt through java

1. First, download the jar package related to org.eclipse.paho.client.mqttv3-1.1.1.jar, or add dependencies to the maven project.

<dependencies>
   <dependency>
    <groupId>org.eclipse.paho</groupId>
    <artifactId>org.eclipse.paho.client.mqttv3</artifactId>
    <version>1.2.0</version>
   </dependency>
 </dependencies>

2. Sending Information

String HOST = "tcp://ip:1883" Server address
String userName = ""  # User name
String password = ""  # Password
String clientId = ""  # 
int qos = 1|2|0	# Level of message
String topic = ""  # Published topics
String count = ""  # Contents published  

Publisher:

 MemoryPersistence persistence = new MemoryPersistence()ï¼›Memory storage
   // Create Client
    MqttClient  client = new MqttClient(String url, String clientId, MemoryPersistence);
    //Create connection parameters
    MqttConnectOptions connOpts = nwe MqttConnectOptions();
    // Keep state in mind when restarting and reconnecting
     connOpts.setCleanSession(false);
     // Set the username of the connection
     connOptis.setUserName(userName);
     connOptis.setPassword(password.toCharArray());  # Parameters are character array types
     // Create connection
     client.connect(connOpts);  # If you do not pass parameters, follow the default
     // Create message
      MqttMessage message = new MqttMessage(content.getBytes());   #  The parameter is the byte array type
    //  Setting the quality of service of messages
      message.setQos(qos);
    //  Publish news
     client.publish(topic, message);
    //  Disconnect
      client.disconnect();
    // Close the client
      client.close();

receiving end

MemoryPersistence memoryPersistence = new MemoryPersistence();
        try {
            MqttClient client = new MqttClient("","",memoryPersistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(false);
            connOpts.setUserName("");
            connOpts.setPassword("".toCharArray());
            client.connect(connOpts);
            // Set the callback function to invoke this method when subscription arrives
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable throwable) {
                    // Called when connection fails
                }

                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    // Subscribe successfully and accept information calls
                    mqttMessage.getPayload(); // Get message content
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                }
            });
            
            client.subscribe("xxx");
            
            client.disconnect();
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

Keywords: Eclipse Mobile Java Maven

Added by netzverwalter on Tue, 01 Oct 2019 23:26:00 +0300