Brief introduction of MQTT protocol and server Installation (I)

Recently, the company used message push in the project. After various screening, it decided to use MQTT protocol. Compared with XMPP, MQTT is more lightweight and consumes less user bandwidth.

MQTT is a TCP/ IP-based publishing/booking protocol for mobile terminal devices that can connect a large number of remote sensors and control devices.

MQTT’s official website can be found at mqtt.org/. mqtt.org/software provides officially recommended apis for various servers and clients in various languages.

The following takes server Apollo 1.6 as an example. We tried to use ActiveMQ before, but the effect was not ideal. We could only achieve one-to-one communication between the server and the client. Anyway, without further ado, the following is in the Windows environment.

Run apache-Apollo-1.6 \bin\ Apollo. CMD to create an instance of myBroker. The server instance contains all configurations. Runtime data, and associated with a server process.

The myBroker folder will be generated in the bin directory. This folder contains a lot of information. Under the etc\ Apollo.xml file, you can configure the server information. The etc\users.properties file contains the user name and password used to connect to the MQTT server, as described later. You can change the original admin=password and then add a new user name and password on a newline.

3, open CMD, run… Apache-apollo-1.6 \bin\mybroker\bin\ Apollo-broker. CMD run Start the server. You can enter http://127.0.0.1:61680/ in your browser to check whether the installation is successful. Number of connections and so on.

After the above simple steps, the server is basically complete, the next article will cover the Android client writing and considerations.

\

Write Android client program to communicate with MQTT server (II)

The API used by the client was MQTT-client at the beginning, but it was found to be full of problems and could not meet the requirements. Later, I used Eclipse Paho, which was officially recommended, and the client code was compiled below. For the convenience of testing, there are two projects: Android and J2SE:

1. Create an Android project MQTTClient

2. MainActivity code is as follows:

package ldw.mqttclient; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; 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.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private TextView resultTv; Private String host = “TCP ://127.0.0.1:1883”; private String userName = “admin”; private String passWord = “password”; private Handler handler; private MqttClient client; private String myTopic = “test/topic”; private MqttConnectOptions options; private ScheduledExecutorService scheduler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); resultTv = (TextView) findViewById(R.id.result); init(); handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if(msg.what == 1) { Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show(); System.out.println(“—————————–“); } else if(MSG. What == 2) {toast.maketext (mainactivity.this, “connection succeeded “, toast.length_short).show(); try { client.subscribe(myTopic, 1); } catch (Exception e) { e.printStackTrace(); }} else if(msg.what == 3) {toast.maketext (mainactivity.this, “connection failed, system is reconnected “, toast.length_short).show(); }}}; startReconnect(); } private void startReconnect() { scheduler = Executors.newSingleThreadScheduledExecutor(); scheduler.scheduleAtFixedRate(new Runnable() { @Override public void run() { if(! client.isConnected()) { connect(); } } }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS); } private void init() {//host = host; test = clientid = clientid; MemoryPersistence = clientid; Client = new MqttClient(host, “test”, new MemoryPersistence()); // options = new MqttConnectOptions(); If this parameter is set to false, the server reserves the connection records of the client. If this parameter is set to true, the server uses a new identity for each connection to the server. Options.setcleansession (true); // set the connection userName options.setUserName(userName); // Set the connection passWord options.setPassword(password.tochararray ()); / / set the options for seconds. Overtime setConnectionTimeout (10); / / set the session for seconds heartbeat Server will be every 1.5 * 20 seconds to the client sends a message to determine whether a client online, but this method doesn’t options. The mechanism of reconnection setKeepAliveInterval (20); SetCallback (new MqttCallback() {@override public void connectionLost(Throwable cause) { Println (“connectionLost———-“); system.out.println (“connectionLost———-“); } @override public void deliveryComplete(IMqttDeliveryToken token) {// Publish will execute here System.out.println(“deliveryComplete———” + token.isComplete()); } @Override public void messageArrived(String topicName, MqttMessage message) throws Exception {//subscribe system.out.println (“messageArrived———-“); Message msg = new Message(); msg.what = 1; msg.obj = topicName+”—“+message.toString(); handler.sendMessage(msg); }}); // connect(); } catch (Exception e) { e.printStackTrace(); } } private void connect() { new Thread(new Runnable() { @Override public void run() { try { client.connect(options); Message msg = new Message(); msg.what = 2; handler.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); Message msg = new Message(); msg.what = 3; handler.sendMessage(msg); } } }).start(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(client ! = null && keyCode == KeyEvent.KEYCODE_BACK) { try { client.disconnect(); } catch (Exception e) { e.printStackTrace(); } } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { super.onDestroy(); try { scheduler.shutdown(); client.disconnect(); } catch (MqttException e) { e.printStackTrace(); }}} \

I used heartbeat reconnection for the project. Set apollo.xml according to the explanation here, mainly set the host connection address. Options also has a setWill method that can be called if the project needs to know if the client is down.

3. Create J2SE project MQTTServer

4. The Server code is as follows:

import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; 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.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttTopic; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; public class Server extends JFrame { private static final long serialVersionUID = 1L; private JPanel panel; private JButton button; private MqttClient client; Private String host = “TCP ://127.0.0.1:1883”; // private String host = “tcp://localhost:1883”; private String userName = “test”; private String passWord = “test”; private MqttTopic topic; private MqttMessage message; private String myTopic = “test/topic”; public Server() { try { client = new MqttClient(host, “Server”, new MemoryPersistence()); connect(); } catch (Exception e) { e.printStackTrace(); } Container container = this.getContentPane(); panel = new JPanel(); Button = new JButton(” button “); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { try { MqttDeliveryToken token = topic.publish(message); token.waitForCompletion(); System.out.println(token.isComplete()+”========”); } catch (Exception e) { e.printStackTrace(); }}}); panel.add(button); container.add(panel, “North”); } private void connect() { MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(false); options.setUserName(userName); options.setPassword(passWord.toCharArray()); / / set the timeout options. SetConnectionTimeout (10); / / set the session time heartbeat options. SetKeepAliveInterval (20); try { client.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { System.out.println(“connectionLost———–“); } @Override public void deliveryComplete(IMqttDeliveryToken token) { System.out.println(“deliveryComplete———“+token.isComplete()); } @Override public void messageArrived(String topic, MqttMessage arg1) throws Exception { System.out.println(“messageArrived———-“); }}); topic = client.getTopic(myTopic); message = new MqttMessage(); message.setQos(1); message.setRetained(true); System. The out. Println (message. IsRetained () + “– — — — — – ratained state”); message.setPayload(“eeeeeaaaaaawwwwww—“.getBytes()); client.connect(options); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Server s = new Server(); s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); s.setSize(600, 370); s.setLocationRelativeTo(null); s.setVisible(true); }} \

The above code is similar to the client code, so I won’t explain it here.

There’s nothing to say, MQTT is as simple as that, but start using it with a few parameters to suit the needs of the project.

\

\

\

\