Use of the MQTT Protocol future mode subscription and release (implemented using Fusesource mqtt-client)

Source: Internet
Author: User
Tags ack set socket socket throwable time interval mqtt broker

Fusesource version: Mqtt-client-1.10.jar

Download Address: https://github.com/fusesource/mqtt-client

Fusesource provides three ways to publish messages:

1. Using a blocking connection (blockingconnection)

2. Using a callback connection (callbackconnection)

3. Use the future-style connection (futureconnection)

Where the callback API is the most complex and the best performance,

The other two are encapsulation of callback APIs. Let's take a brief look at how the callback API is used.

1. Client implementation:

Package Com.ctfo.mqtt.client.demo.fusesource;

Import java.net.URISyntaxException;
Import Org.fusesource.mqtt.client.Future;
Import org.fusesource.mqtt.client.FutureConnection;
Import Org.fusesource.mqtt.client.MQTT;
Import Org.fusesource.mqtt.client.Message;
Import Org.fusesource.mqtt.client.QoS;

Import Org.fusesource.mqtt.client.Topic; /** * Subscribe to the topic in future mode */public class Mqttfutureclient {private final static String connection_string = "tcp://192.
	168.13.240:1883 ";
	Private Final Static Boolean Clean_start = true;
	Private final static short keep_alive = 30;//low-power network, but need to get data in time, heartbeat 30s private final static String client_id = "CLIENT";
		public static topic[] topics = {New Topic ("Mqtt/aaa", qos.exactly_once), New Topic ("mqtt/bbb", qos.at_least_once),
	
	New Topic ("MQTT/CCC", Qos.at_most_once)};
	Public final static Long Reconnection_attempt_max = 6;

	Public final static long reconnection_delay = 2000; Public final static int send_buffer_size = 2 * 1024 * 1024;//Send maximumBuffer for 2M public static void Main (string[] args) {//Create Mqtt object Mqtt mqtt = new Mqtt ();
			try {//Set the IP and Port mqtt.sethost (connection_string) of the MQTT broker;
			Emptying session information before connecting Mqtt.setcleansession (Clean_start);
			Set number of reconnection times Mqtt.setreconnectattemptsmax (Reconnection_attempt_max);
			Set the time interval for mqtt.setreconnectdelay (reconnection_delay);
			Set the heartbeat Time Mqtt.setkeepalive (keep_alive);
			Sets the size of the buffer mqtt.setsendbuffersize (send_buffer_size);

			Set the client ID Mqtt.setclientid (client_id);
			Gets the connection object for Mqtt blockingconnection final futureconnection connection = Mqtt.futureconnection ();
			Connection.connect ();
			Connection.subscribe (topics);
				while (true) {future<message> futruemessage = connection.receive ();  
				Message message = Futruemessage.await (); System.out.println ("mqttfutureclient.receive Message" + "Topic Title:" + message.gettopic () + "context:" + Strin
			G.valueof (Message.getpayloadbuffer ())); }} catch (URISyntaxException e) {//TODO auto-generated catch block E.printstacktrace ();
		} catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
 } finally {}}}
2. Service-Side implementation:

Package Com.ctfo.mqtt.client.demo.fusesource;

Import java.net.URISyntaxException;
Import Org.fusesource.hawtbuf.Buffer;
Import Org.fusesource.hawtbuf.UTF8Buffer;
Import Org.fusesource.hawtdispatch.Dispatch;
Import Org.fusesource.mqtt.client.Callback;
Import org.fusesource.mqtt.client.CallbackConnection;
Import org.fusesource.mqtt.client.FutureConnection;
Import Org.fusesource.mqtt.client.Listener;
Import Org.fusesource.mqtt.client.MQTT;
Import Org.fusesource.mqtt.client.QoS;
Import Org.fusesource.mqtt.client.Topic;
Import Org.fusesource.mqtt.client.Tracer;

Import Org.fusesource.mqtt.codec.MQTTFrame; /** * Publish Theme with future mode * */public class Mqttfutureserver {private final static String connection_string = "TC  
     p://192.168.13.240:1883 ";  
     Private Final Static Boolean Clean_start = true;
     Private final static String client_id = "Server";  
      Private final static short keep_alive = 30;//low-power network, but need to get data in time, heartbeat 30s public static topic[] topics = {               New Topic ("Mqtt/aaa", qos.exactly_once), New Topic ("mqtt/bbb", qos.at_least_once),  
     
     New Topic ("MQTT/CCC", Qos.at_most_once)};  
     Public final static long reconnection_attempt_max=6;  
       
     Public final static long reconnection_delay=2000;    Public final static int send_buffer_size=2*1024*1024;//send maximum buffer to 2M public static void Main (string[] args)  
         {Mqtt Mqtt = new Mqtt ();  
             try {//==MQTT Setup description//Set IP mqtt.sethost (connection_string) on the server;  
             Empty session information before connection, if set to FALSE,MQTT server will persist the principal subscription and ACK location of client session, default is True Mqtt.setcleansession (Clean_start);  
             Set the heartbeat time, define the maximum time interval of the message from the client, the server can determine whether the connection with the client has been disconnected, so as to avoid TCP/IP timeout for a long time waiting for mqtt.setkeepalive (keep_alive); Sets the client ID that is 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 time Mqtt.setClientId (client_id);
 			 Server Authentication User name//mqtt.setusername ("admin");
 			 
 			 Server Authentication Password//mqtt.setpassword ("admin");
 			 /*//set content of "will" message, default is zero length message mqtt.setwillmessage ("Willmessage");
 			 Set QoS for "will" message, default to Qos.atmostonce Mqtt.setwillqos (qos.at_least_once);
 			 True Mqtt.setwillretain (TRUE) if you want to have the retain option when publishing a "will" message;
 			 Set the topic of "will" message, if the connection between client and server is interrupted unexpectedly, the server will publish the client's "Wills" message mqtt.setwilltopic ("Willtopic"); *///== Failed to reconnect settings description//Set the number of reconnection times, the client has connected to the server, but for some reason the maximum number of retries when the connection is dropped, the client will return an error.  
             -1 means no retry limit, default is-1 Mqtt.setreconnectattemptsmax (Reconnection_attempt_max);  
             Set the time interval for reconnection, the number of milliseconds for the first reconnection interval, and the default is 10ms Mqtt.setreconnectdelay (reconnection_delay); 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-1//mqtt.setconnectattemptsmax (10L);
             The number of milliseconds for the reconnection interval is 30000ms//mqtt.setreconnectdelaymax (30000L); Sets the reconnection exponential regression. Set to 1 to deactivate exponential regression, which defaults to 2//mqtt.setreconnectbackoffmulTiplier (2);
             = = Socket setting description//Set socket receive buffer size, default is 65536 (64k)//mqtt.setreceivebuffersize (65536);  
             Sets the socket send buffer size, which defaults to 65536 (64k) mqtt.setsendbuffersize (send_buffer_size);
             
             Set the traffic Type or service Type field to send the packet header, default to 8, which means maximum throughput transmission Mqtt.settrafficclass (8); = = Bandwidth Limit setting description mqtt.setmaxreadrate (0);//Set the maximum receive rate for the connection, in BYTES/S. The default is 0, which is unlimited mqtt.setmaxwriterate (0);//sets the maximum send rate for the connection, in BYTES/S. The default is 0, which is unlimited//== select message Distribution queue//If no method setdispatchqueue is called, the client will create a new queue for the connection.
             
            If you want to implement multiple connections using a common queue, it is a convenient implementation method to explicitly specify the queue//mqtt.setdispatchqueue (Dispatch.createqueue ("mqtt/aaa"));  = = Set Tracker/* Mqtt.settracer (New Tracer () {@Override public void
                 OnReceive (Mqttframe frame) {System.out.println ("recv:" +frame);
     } @Override            public void OnSend (Mqttframe frame) {System.out.println ("send:" +frame);
                     } @Override public void debug (String message, Object ... args) {
                 System.out.println (String.Format ("Debug:" +message, args)); }}); *//Use the future to create a connection final futureconnection connection= Mqtt.fut  
             Ureconnection ();  
             Connection.connect ();  
             int count=1;  
                 while (true) {count++;  
                 For publishing messages, the current phone segment does not need to send messages to the server//topic content String message= "Hello" +count+ "MQTT ...";  
                 String topic = "MQTT/BBB";  
                 Connection.publish (topic, message.getbytes (), qos.at_least_once, false);  
System.out.println ("Mqttfutureserver.publish Message" + "Topic Title:" +topic+ "context:" +message);                   
             }//using the callback API/* Final Callbackconnection CALLBACKCONNECTION=MQ
            Tt.callbackconnection (); Connection monitor Callbackconnection.listener (new Listener () {//Receive subscription topic posted message @Override public vo ID onpublish (utf8buffer topic, Buffer Body, Runnable ack) {System.out.println ("=============receive msg==============
				= = "+new String (Body.tobytearray ()));
			Ack.run (); }//Connection failed @Override public void OnFailure (Throwable value) {System.ou
              T.println ("===========connect failure===========");
             Callbackconnection.disconnect (NULL); }//Connection disconnected @Override public void ondisconnected () {System.out.print
             ln ("====mqtt disconnected====="); }//Connection succeeded @Override public void onconnected () {System.out.println ("= = ==mqtt Connected===== ");
             }
            }); Connection Callbackconnection.connect (new callback<void> () {//connection failed public Vo ID onfailure (throwable value) {System.out.println ("============ Connection failed:" +value.getlocalizedmessage () + "=
                 ===========");
                     }//Connection succeeded public void onsuccess (void V) {//subscription topic
                     Topic[] topics = {New Topic ("mqtt/bbb", Qos.at_least_once)};
                      Callbackconnection.subscribe (topics, new callback<byte[]> () {//Subscription theme Success
                         public void onsuccess (byte[] qoses) {System.out.println ("======== subscription succeeded =======");
                          }//Subscription topic failed public void OnFailure (Throwable value) {
                          System.out.println ("======== subscription failed ======="); CallbackConnection.disconnect (NULL);
                      }
                     }); Publish Message Callbackconnection.publish ("MQTT/BBB", ("Hello"). GetBytes (), Qos.at_least_once, True, new Cal Lback<void> () {public Void onsuccess (Void v) {System.out.print
                         ln ("=========== message published successfully ============"); } public void OnFailure (Throwable value) {System.out.println ("========
                          Message Publishing failed ======= ");
                         Callbackconnection.disconnect (NULL);
            
                 }
                     });
             }
             });  
         */} catch (URISyntaxException e) {e.printstacktrace ();  
         } catch (Exception e) {e.printstacktrace ();
 }  
     }  

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.