基于javaweb语言的MQTT客户端

基于javaweb的MQTT客户端

本客户端使用了org.eclipse.paho.client.mqttv3-1.2.0的插件,在myeclipse上实现,并且连接了数据库,前端实现数据的发送接收,并且把接收的数据存入数据库。

MATT简介

MQTT(Message Queuing Telemetry Transport,消息队列遥测传输协议),是一种基于发布/订阅(publish/subscribe)模式的"轻量级"通讯协议,该协议构建于TCP/IP协议上,由IBM在1999年发布。MQTT最大优点在于,可以以极少的代码和有限的带宽,为连接远程设备提供实时可靠的消息服务。作为一种低开销、低带宽占用的即时通讯协议,使其在物联网、小型设备、移动应用等方面有较广泛的应用。

MQTT是一个基于客户端-服务器的消息发布/订阅传输协议。MQTT协议是轻量、简单、开放和易于实现的,这些特点使它适用范围非常广泛。在很多情况下,包括受限的环境中,如:机器与机器(M2M)通信和物联网(IoT)。其在,通过卫星链路通信传感器、偶尔拨号的医疗设备、智能家居、及一些小型化设备中已广泛使用。

首先建立两个servlet(连接前端,接收数据)

package com.example.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.activemq.mqtt.MyMqttRecieveMessage;

public class subscribeservlet extends HttpServlet {

	/**
		 * Destruction of the servlet. 
*/
public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("subscribeservlet"); String Topic=request.getParameter("Topic"); System.out.println (Topic); String QOS=request.getParameter("QOS"); int Qos= Integer.parseInt(QOS); System.out.println ( Qos); MyMqttRecieveMessage.recieve(Topic,Qos); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * Initialization of the servlet.
* * @throws ServletException if an error occurs */
public void init() throws ServletException { // Put your code here } }
package com.example.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;

import com.activemq.mqtt.MyMqttRecieveMessage;
import com.activemq.mqtt.Server;





public class Mainservlet extends HttpServlet {

	/**
	 * Destruction of the servlet. 
*/
public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // MyMqttRecieveMessage.recieve("webServer"); System.out.println ("servlet已运行"); String Topic=request.getParameter("Topic"); System.out.println (Topic); String QOS=request.getParameter("QOS"); int Qos= Integer.parseInt(QOS); String Payload=request.getParameter("Payload"); System.out.println (Payload); try { Server server=new Server(Topic,Qos,Payload); } catch (MqttException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } request.setAttribute("Topic", Topic); request.setAttribute("QOS",QOS); request.setAttribute("Payload",Payload); request.getRequestDispatcher("/publishlist.jsp").forward(request,response); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * Initialization of the servlet.
* * @throws ServletException if an error occurs */
public void init() throws ServletException { // Put your code here } }

##连接MQTT服务器代码

package com.activemq.mqtt;
 
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.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
 
//import com.wanwei.ilogger.ilogger;
 
public class MyMqttRecieveMessage {
 
	//private static int QoS = 1;
	private static String Host = "tcp://127.0.0.1:1883";
	private static MemoryPersistence memoryPersistence = null;
	private static MqttConnectOptions mqttConnectOptions = null;
	private static MqttClient mqttClient  = null;
	
	public static void init(String clientId) {
		mqttConnectOptions = new MqttConnectOptions();
		memoryPersistence = new MemoryPersistence();
		//ilogger ilogger = new ilogger("MyMqttRecieveMessage", "init");
		if(null != memoryPersistence && null != clientId && null != Host) {
			try {
				 mqttClient = new MqttClient(Host, clientId, memoryPersistence);
			} catch (MqttException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else {
			//ilogger.logerr("memoryPersistence clientId Host 有空值");
		}
		
		if(null != mqttConnectOptions) {
			mqttConnectOptions.setCleanSession(true);
			mqttConnectOptions.setConnectionTimeout(30);
			mqttConnectOptions.setKeepAliveInterval(45);
			if(null != mqttClient && !mqttClient.isConnected()) {
				mqttClient.setCallback(new PushCallback());
				try {
					mqttClient.connect();
				} catch (MqttException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			}else {
				//ilogger.logerr("mqttClient is error");
			}
		}else {
		//	ilogger.logerr("mqttConnectOptions is null");
		}
	}
	
	
    public static void recieve(String topic,int QoS) {
        int[] Qos = {QoS};
        String[] topics = {topic};
    //    ilogger ilogger = new ilogger("MyMqttRecieveMessage", "subTopic");
        if(null != mqttClient && mqttClient.isConnected()) {
        	if(null!=topics && null!=Qos && topics.length>0 && Qos.length>0) {
        		try {
        			mqttClient.subscribe(topics, Qos);
        			System.out.print("订阅成功............");
        		} catch (MqttException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
        	}else {
        	//	ilogger.logerr("there is error");
        	}
        }else {
        	init("subclient");
        	recieve(topic,QoS);
        }
    }
 
 
}
	

/**  
 * @Title: PushCallback.java
 * @Package org.chisj.mqtt
 * @Description: TODO
 * @author chisj [email protected]
 * @date 2017年4月1日
 */
package com.activemq.mqtt;
   
 import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
 import org.eclipse.paho.client.mqttv3.MqttCallback;  
 import org.eclipse.paho.client.mqttv3.MqttMessage;  
   
 /**  
  * 发布消息的回调类  
  *   
  * 必须实现MqttCallback的接口并实现对应的相关接口方法CallBack 类将实现 MqttCallBack。  
  * 每个客户机标识都需要一个回调实例。在此示例中,构造函数传递客户机标识以另存为实例数据。
  * 在回调中,将它用来标识已经启动了该回调的哪个实例。  
  * 必须在回调类中实现三个方法:  
  *   
  *  public void messageArrived(MqttTopic topic, MqttMessage message)接收已经预订的发布。  
  *   
  *  public void connectionLost(Throwable cause)在断开连接时调用。  
  *   
  *  public void deliveryComplete(MqttDeliveryToken token))  
  *  接收到已经发布的 QoS 1 或 QoS 2 消息的传递令牌时调用。  
  *  由 MqttClient.connect 激活此回调。  
  *   
  */    
 public class PushCallback implements MqttCallback {  
   
     public void connectionLost(Throwable cause) {  
         // 连接丢失后,一般在这里面进行重连  
         System.out.println("连接断开,可以做重连");  
     }  
     
     public void deliveryComplete(IMqttDeliveryToken token) {
         System.out.println("deliveryComplete---------" + token.isComplete());  
     }
 
     public void messageArrived(String topic, MqttMessage message) throws Exception {
         // subscribe后得到的消息会执行到这里面  
         System.out.println("接收消息主题 : " + topic);  
         System.out.println("接收消息Qos : " + message.getQos());  
         System.out.println("接收消息内容 : " + new String(message.getPayload()));  
     }  
 }

/**  
 * @Title: Server.java
 * @Package org.chisj.mqtt
 * @Description: TODO
 * 
 * 
 */
package com.activemq.mqtt;
 
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.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
 
/**
 * ClassName: Server 
 * @Description: TODO
 * @author
 * @date 
 */
//发布
public class Server {
 
   
	public static final String HOST = "tcp://127.0.0.1:1883";
    public static  String TOPIC ;
   // public static final String TOPIC125 = "toclient/125";
    private static final String clientid = "server";

    private MqttClient client;
    private MqttTopic topic;
  //  private MqttTopic topic125;
    private String userName = "admin";
    private String passWord = "public";
 
    private MqttMessage message;
 
     public Server(String topic1 ,int id,String payload) throws MqttException {
    	     this.TOPIC=topic1;
    	      client = new MqttClient(HOST, clientid, new MemoryPersistence());
              connect();
            
		      message = new MqttMessage();
		      message.setQos(id);
		      message.setRetained(true);
		      message.setPayload(payload.getBytes());
		      publish(topic ,message);
         // MemoryPersistence设置clientid的保存形式,默认为以内存保存
         
     }
 
     private void connect() {
         MqttConnectOptions options = new MqttConnectOptions();
         options.setCleanSession(false);
         options.setUserName(userName);
         options.setPassword(passWord.toCharArray());
         // 设置超时时间
         options.setConnectionTimeout(10);
         // 设置会话心跳时间
         options.setKeepAliveInterval(20);
         try {
             client.setCallback(new PushCallback());
             client.connect(options);
             topic = client.getTopic(TOPIC);
         //    topic125 = client.getTopic(TOPIC125);
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
 
     public void publish(MqttTopic topic , MqttMessage message) throws MqttPersistenceException,
             MqttException {
         MqttDeliveryToken token = topic.publish(message);
         token.waitForCompletion();
         System.out.println("message is published completely! "
                 + token.isComplete());
     }
 
//     public static  void publicmessage(String topic,String message,int Qos) throws MqttException {
//         Server server = new Server();
//         server.message = new MqttMessage();
//         server.message.setQos(2);
//         server.message.setRetained(true);
//         server.message.setPayload("给客户端124推送的信息".getBytes());
//         server.publish(server.topic , server.message);
//        System.out.println(server.message.isRetained() + "------ratained状态");
//    }

 }

基于javaweb语言的MQTT客户端_第1张图片
只需要创建jsp前台页面,发送到servlet则可调用其他几个类,并且我把消息封装成类,插入数据库。

你可能感兴趣的:(MQTT)