use of MQTT Mosquitto + websocktes liunx Environment
installation of 1.mosquitto
If you need Mosquitto support websocktes you need to install Libwebsockets first
Libwebsockets Download Address Https://github.com/warmcat/libwebsockets
Mosquitto Download Address https://mosquitto.org/download/
Installation of 1.1 Libwebsockets
A. After unpacking the Libwebsockets package, create the build directory Mikdir build in the current wood directory
B. CD build directory execution CMake. Need to install CMake if not installed CMake
C. Perform installation CMake install
D. Clear install temp file CMake clean
Installation of 1.2 Mosquitto
A. After extracting the file vi config.mk file
B. Modify With_websockets:=yes must be set before installation, otherwise it will not be supported Websocktes
C. Compiling make
During the compilation process you may need to install OpenSSL, C-ares, libuuid, libraries that need to be installed by Yum to install
The use of Yum is not a word.
D. Execute installation command make install
E. Clear install temp file make clean
1.3 Configuration of Mosquitto.cnof files
A.mosquitto default using Mosquitto user to start or modify startup user
B. Adding a websocktes configuration for Mosquitto
Mosquitto is to support multiple listeners to configure multiple listeners to configure multiple listener and protocol
Mosquitto default port of 1883 the default protocol is MQTT
If you need to support both MQTT and websocktes, you need to open Mosquitto default ports and protocol
1.4 Start Mosquitto
My Mosquitto is installed under, Usr/loacl
There will be a default mosquitto.conf file in the ETC directory during installation
I'm using mosquitto.conf in the installation directory.
Mosquitto-c/user/loacl/mosquitto/mosquitto.conf &
A missing libmosquittopp.so.1 libwebsockets.so.10 file may be prompted during startup
These two files are installed by default into the/user/loacl/lib directory
The 32-bit side needs to copy the two files to the/usr/lib directory if you are over your system.
The 64-bit side needs to copy the two files to the/usr/lib64 directory if you are over your system.
1.5 Configuration of Mosquitto logs
A.mosquitto The default log directory/var/log/messages or similar
Log_dest The log is printed to the console by default
When Log_dest is set to topic, it is sent as a message to the system theme you subscribed to.
Mosquitto's system topics begin with a $SYS document address https://mosquitto.org/man/mosquitto-8.html
Log_type Types of logs
2.mosquitto java-side code
Package Test.test.mqtt.mosquitto;
Import Org.eclipse.paho.client.mqttv3.IMqttActionListener;
Import Org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
Import Org.eclipse.paho.client.mqttv3.IMqttMessageListener;
Import Org.eclipse.paho.client.mqttv3.IMqttToken;
Import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
Import Org.eclipse.paho.client.mqttv3.MqttCallback;
Import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
Import org.eclipse.paho.client.mqttv3.MqttException;
Import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
/** * @author Sun Yunfei */public class Mqttmessage {private static final String HOST = "tcp://192.168.0.122:1883";
private static final String TOPIC = "$SYS/broker/log/#";
private static final String CLIENTID = "Mqttserver";
public static mqttasyncclient client; public static void Init () {try {client = new Mqttasyncclient (HOST, CLIENTID, New Memorypersistence ()
); Client.setcallback (New MQTTCALLBAck () {@Override public void Connectionlost (Throwable cause) {System
. OUT.PRINTLN ("Connectionlost"); } @Override public void messagearrived (String topic, Org.eclipse.paho.client.mqttv3.MqttM
Essage message) throws Exception {System.out.println (message.tostring () + "FSDFSFDFSDFSDF");
} @Override public void Deliverycomplete (Imqttdeliverytoken token) {
System.out.println ("Deliverycomplete");
}
}); Client.connect (initoptions (), NULL, new Imqttactionlistener () {@Override public void Onsu Ccess (Imqtttoken asyncactiontoken) {System.out.println ("link succeeded.
"); try {client.subscribe (TOPIC, 0, New Imqttmessagelistener () {@Overrid
E public void messagearrived (String topic, Org.eclipse.paho.client.mqttv3.MqttMessage message) throws Exception
{System.out.println (message.tostring ());
System.out.println (Client.getpendingdeliverytokens (). length);
char i = 65;
Simplelogformatter.left ("sdddd", ten, I);
}
});
} catch (Mqttexception e) {e.printstacktrace (); }} @Override public void OnFailure (Imqtttoken asyncactiontoken, throwabl E exception) {System.out.println ("link failed.
");
}
});
} catch (Mqttexception e) {e.printstacktrace (); }} private static Mqttconnectoptions initoptions () {mqttconnectoptions options = new MqttconneCtoptions (); Options.setautomaticreconnect (TRUE);//default re-connect options.setcleansession (FALSE);//Clear Session Options.setconnect Iontimeout (60);//timeout in seconds Options.setkeepaliveinterval (60)//Heartbeat time in seconds//options.setwill (TOPIC, " Failure ". GetBytes (), 0, false);
If the link fails, a message is sent to return to the options;
} public static void Main (string[] args) {init (); } public static void Send (string[] args) throws Mqttpersistenceexception, mqttexception {mqttmessage.client . Publish ("Service", "1111111". GetBytes (), 1, True, NULL, new Imqttactionlistener () {@Override PU
Blic void onsuccess (Imqtttoken asyncactiontoken) {System.out.println ("Send------------------onsuccess");
} @Override public void OnFailure (Imqtttoken asyncactiontoken, throwable exception) {
System.out.println ("Send------------------onfailure");
}
}); }
}
3.websocktes code needs to introduce https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js
Host = ' 192.168.0.112 ';
hostname or IP address port = 1884; Topic = ' PC ';
Topic to subscribe to USETLS = false;
Username = null;
Password = null;
Username = "Jjolie";
Password = "AA";
Cleansession = true;
<script type= "Text/javascript" > var mqtt;
var reconnecttimeout = 2000;
function Mqttconnect () {mqtt = new Paho.MQTT.Client ("192.168.0.112",
1884, "pc_111"); var options = {timeout:3, usessl:usetls, Cleansession:cleansession, on Success:onconnect, onfailure:function (message) {$ (' #status '). Val ("Connection failed:" + M
Essage.errormessage + "retrying");
SetTimeout (Mqttconnect, reconnecttimeout);
}
};
Mqtt.onconnectionlost = Onconnectionlost;
mqtt.onmessagearrived = onmessagearrived; if (username! = null) {OPtions.username = UserName;
Options.password = password; } console.log ("host=" + Host + ", port=" + port + "TLS =" + Usetls + "Username=" + username + "password=" + pas
Sword);
Mqtt.connect (options);
} function OnConnect () {$ (' #status '). Val (' Connected to ' + Host + ': ' + port); Connection succeeded;
Subscribe to our topic Mqtt.subscribe (topic, {qos:0});
$ (' #topic '). val (topic);
} function Onconnectionlost (response) {setTimeout (mqttconnect, reconnecttimeout); $ (' #status '). Val ("Connection lost:" + Responseobject.errormessage + ").
Reconnecting ");
};
function onmessagearrived (message) {var topic = Message.destinationname;
var payload = message.payloadstring;
$ (' #ws '). Prepend (' <li> ' + topic + ' = ' + payload + ' </li> ');
};
function Button_onclick () {//Here write the statement you want to execute var TP = $ (' #sendtopic '). Val (); var vaL = $ (' #textsend '). Val (); if (tp== ' | | |
val== ') {alert ("no AAA");
Return
} var message = new Paho.MQTT.Message (val);
Message.destinationname = TP;
message.qos=0;
Mqtt.send (message);
Mqtt.publish (TP, 0, Val);
$ (' #ws '). Prepend (' <li> ' + tp + ' = ' + val+ ' </li> ');
};
$ (document). Ready (function () {mqttconnect ();
}); </script>