The last time we talked a little bit about some of the MQTT protocols, here's a concrete Java implementation of the last knowledge.
Now come to the concrete point of the realization of this step. The middle of the time is also a bit long.
MQTT messages are sent and subscribed to an MQTT server, without an MQTT server, and your clients cannot subscribe to and send messages. So at the very beginning, you can selectively install an MQTT server on top of your computer. Mqtt server There are many, you can also find some installation tutorials on the Internet, here because and I want to talk about the content is not very related, so no longer tired.
There is no concept of sender and receiver in the MQTT protocol, and all connections are users, so an MQTT connection can either send messages or receive messages. is equal to all connections are clients. The following is the same with my client code, because the company receives the information from the first to be authenticated, the successful certification before receiving useful information. At this point, the client in accordance with the device information to control the device above the gateway, to achieve the purpose of remote control equipment. Because to use the server to forward the message, so the test for the server is also more important, but I use the company's server, so this piece I know less. But I have some tools here, Google Chrome plugin mqttlens. Might help you. (need to flip through walls)
There are many libraries used by MQTT, and the following URLs also list the MQTT supported libraries, both Java and C. The website is as follows: Https://github.com/mqtt/mqtt.github.io/wiki/libraries. Because at the beginning of my contact is relatively shallow, using: Fusesource mqtt-client. So Java demo is based on this library, but later and spring integration found some problems, because spring supports only one library, is the Eclipse Paho Java. But the principle is the same, we can decide for themselves, my simple demo code is based on Fusesource mqtt-client. In the next spring and MQTT integration, Eclipse Paho Java is used.
Here is a specific idea, this way my code is based on the company's gateway requirements, so first of all, say a company gateway specific process. First, the gateway will always send the authentication message, waiting for client authentication, after the client authentication passes, will send the concrete useful information. The client then sends control commands according to the gateway information, reaching the control's purpose. In this process, the client has subscriptions and sends, so a client exercises the sending and subscribing messages. This is the company's specific operating procedures. Let's talk about the process of code.
You can use the jar package at runtime or MAVEN, but be aware of the version when using MAVEN.
Specific jar packages and Maven dependencies at URL: https://gitee.com/iots/mqtt-client
Dependencies are:
<dependency> <groupId>org.fusesource.mqtt-client</groupId> <artifactId> Mqtt-client</artifactid> <version>1.12</version></dependency>
Start writing the demo below
First configure some of the MQTT configuration, configuration is more, and cumbersome.
The main is to configure the host number and port number, according to their own configuration to write code, in the configuration of some other details configuration, mainly connected with the connection.
The code is as follows:
//MQTT Setup Instructions//Set the host numberMqtt.sethost ("tcp://10.168.5.208:1883"); //used to set the ID of the client session. At Setcleansession (false); When invoked, the MQTT server uses the ID to obtain the appropriate session. This ID should be less than 23 characters and is automatically generated by default based on native address, port, and timeMqtt.setclientid ("876543210"); //if set to FALSE,MQTT server will persist the principal subscription and ACK location for client sessions, the default is TrueMqtt.setcleansession (false); //defines the maximum number of seconds that a client is sent a message, and the server can determine whether the connection to the client has been disconnected, thus avoiding long waits for TCP/IP timeoutsMqtt.setkeepalive (( Short) 60); //Server authenticated user nameMqtt.setusername ("admin"); //Server Authentication PasswordMqtt.setpassword ("admin"); //set the topic of "will" message, if the connection between client and server is interrupted unexpectedly, the server publishes the client's "Wills" messageMqtt.setwilltopic ("Willtopic"); //set the content of the "will" message by default to a zero-length messageMqtt.setwillmessage ("Willmessage"); //QoS Setting "will" message, default is Qos.atmostonceMqtt.setwillqos (qos.at_least_once); //true if you want to have the retain option when publishing a "will" messageMqtt.setwillretain (true); //Set VersionMqtt.setversion ("3.1.1"); //Description of failed reconnection settings//when the client first connects to the server, the maximum number of retries for the connection exceeds the number of times the client will return an error. -1 means no retry limit, default is-1Mqtt.setconnectattemptsmax (10L); //The client will return an error if the client has connected to the server, but the maximum number of retries is exceeded for some reason. -1 means no retry limit, default is-1Mqtt.setreconnectattemptsmax (3L); //number of milliseconds for first reconnection interval, default is 10msMqtt.setreconnectdelay (10L); //number of milliseconds for reconnection interval, default is 30000msMqtt.setreconnectdelaymax (30000L); //sets the reconnection exponential regression. Set to 1 to deactivate exponential regression, which defaults to 2Mqtt.setreconnectbackoffmultiplier (2); //Socket Setup Instructions//sets the socket receive buffer size, which defaults to 65536 (64k)Mqtt.setreceivebuffersize (65536); //set the socket send buffer size, default to 65536 (64k)Mqtt.setsendbuffersize (65536); //set the traffic type or service Type field to send the packet header, which defaults to 8, which means maximum throughput transmissionMqtt.settrafficclass (8); //Bandwidth Throttling Settings Description//sets the maximum receive rate for the connection, in BYTES/S. The default is 0, which is unlimitedMqtt.setmaxreadrate (0); //sets the maximum send rate for the connection, in BYTES/S. The default is 0, which is unlimitedMqtt.setmaxwriterate (0); //Select message Distribution queue//If no method setdispatchqueue is called, the client creates a new queue for the connection. Explicitly specifying a queue is a convenient implementation method if you want to implement multiple connections using a common queueMqtt.setdispatchqueue (Dispatch.createqueue ("foo"));
The above are some configuration issues, the specific circumstances of their own decision configuration. The specific configuration can also refer to the following URL, this URL also has a detailed description: Https://gitee.com/iots/mqtt-client.
Let's talk about connecting and subscribing and sending topics below
Fusesource provides three MQTT client APIs, namely, the blocking API, the futur-based API, and the callback API.
Where the blocking API is a connection that establishes a connection in the Mqtt.connectblocking method and provides a blocking API.
The futur-based API is to establish a connection in the Mqtt.connectfuture method, which provides you with a connection to the combined futur. The connection to all operations is non-blocking, and the result is returned.
The callback API is the most complex and performs best, and the other two are encapsulated in the callback API.
Because the callback API is a bit complex, it is now just an encapsulation of the callback API. Is the first two, the difference between the top two is a block, the second is not blocking. The following starts the code demonstration.
The first blocking API. The code is as follows:
//using the future connectionFutureconnection connection =mqtt.futureconnection (); Future<Void> F1 =Connection.connect (); F1.await (); //Subscribe to Messagesfuture<byte[]> F2 = Connection.subscribe (NewTopic[] {NewTopic ("DATASOURCES/1/1", Qos.at_least_once)}); // byte[] qoses =f2.await (); //sends an authentication message. //future<void> F3 = Connection.publish ("foo", "Hello". GetBytes (),//qos.at_least_once, false); //Receive subscription messages :future<message> receive =connection.receive (); //print the message.Message message =receive.await (); System.out.println (String.valueof (Message.getpayloadbuffer ())); //ResponseMessage.ack (); //future<void> F4 =Connection.disconnect (); F4.await ();
The third is the hardest, my side of the code is a bit messy, directly on the code bar.
//MonitorConnection.listener (NewListener () {@Override Public voidonpublish (Utf8buffer topicmsg, Buffer msg, Runnable ack) {//Utf-8 is used for dealing with the garbledString topic =Topicmsg.utf8 (). toString (); String Payload=Msg.utf8 (). toString (); SYSTEM.OUT.PRINTLN (Topic+ " " +payload); String amsg=authenticationsenddemo.authentication (topic, payload); if(Topic.equals ("Datasources/req")) { //re-starting a blocking threadConnection.getdispatchqueue (). Execute (NewRunnable () { Public voidrun () {Connection.publish ("Datasources/17/01/req_ack", Amsg.getbytes (), Qos.at_least_once,false, NewCallback<void>() {@Override Public voidonsuccess (Void args) {//indicates a successful publishing topicSystem.out.println ("published Successfully! "); System.out.println ("Posted Messages" +amsg); } @Override Public voidonfailure (Throwable throwable) {//indicates a publishing topic failedSystem.out.println ("Publish failed! "); } }); } }); } //indicates successful monitoringAck.run (); } @Override Public voidonfailure (throwable value) {//indicates that the listener failed } //execute only once if connection is ended@Override Public voidondisconnected () {//indicates that a disconnected connection was heardSYSTEM.OUT.PRINTLN ("Disconnect!! "); } //execute only once when connecting started@Override Public voidonconnected () {//indicates that the connection was heard successfullySystem.out.println ("haha"); System.out.println (); } });
Because of the use of the code in the thread and callback, I am not very good for these two mastery, and no longer here, the big guy knows better writing the best advice. Thank you here.
Three kinds of writing are finished, the following talk about feelings and problems encountered in the middle.
Thought to see the specific document is too much, and now the company is busy to catch the project, my side of the time is not a lot, the code after finishing there is time to say. I feel that the most important thing is the understanding of the Protocol, these are more important than the above code, because your final code is still to be integrated with the project, and spring integration you will find that these are the framework provided, all you need to do is to fill in the parameters, But the solution to the problems encountered in integration is that you get from writing the above code.
Because the code is just beginning to be written, the comments in the code are also very numerous, and there is no longer a comment. Write the above code when encountered a lot of problems, the solution of the site are in my first MQTT blog, such as the official website of Mqtt, online articles are copied, or smattering (I also). In the end it is to see their own deep experience.
That's it, it's over.
Mqtt Simple Demo (Java)