package net.engyne.sdk; import java.util.ArrayList; import java.util.Random; 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.MqttPersistenceException; import org.eclipse.paho.client.mqttv3.MqttTopic; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import net.sf.json.JSONObject; public class EngyneMqtt { private MqttClient client; private MqttConnectOptions options = new MqttConnectOptions(); private EngyneCallback engynecallback; private MqttCallback callback; private String clientid; private String headimgurl; private String nickname; private int admin; private ArrayList<String> topicList=new ArrayList<String>(); public EngyneCallback getEngynecallback() { return engynecallback; } public void setEngynecallback(EngyneCallback engynecallback) { this.engynecallback = engynecallback; } public EngyneMqtt(String host,String clientid,EngyneCallback engynecallback,String headimgurl,String nickname,int admin) { this.headimgurl=headimgurl; this.nickname=nickname; this.admin=admin; this.engynecallback=engynecallback; this.clientid=clientid; // MemoryPersistence设置clientid的保存形式,默认为以内存保存 try { client = new MqttClient(host, clientid, new MemoryPersistence()); } catch (MqttException e) { // TODO Auto-generated catch block e.printStackTrace(); } callback = new PushCallback(); client.setCallback(callback); options = new MqttConnectOptions(); options.setCleanSession(true); options.setKeepAliveInterval(60); } /** * 连接mqtt消息服务器,同时设置了断开重连的功能 */ public void connect() { boolean tryConnecting = true; while (tryConnecting) { try { client.connect(options); } catch (Exception e1) { e1.printStackTrace(); } if (client.isConnected()) { System.out.println("Connected."); tryConnecting = false; } else { pause(); } } } public void pause() { try { Thread.sleep(1000); } catch (InterruptedException e) { // Error handling goes here... } } public void subscribe(String topic, int qos) { try { client.subscribe(topic, qos); topicList.add(topic); } catch (MqttException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void unsubscribe(String topic) { try { client.unsubscribe(topic); topicList.remove(topic); } catch (MqttException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void publish(String topic,String content) { int qos=2; boolean retained=false; byte[] payload=content.getBytes(); try { client.publish(topic, payload, qos, retained); } catch (MqttPersistenceException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MqttException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static String getRandomString(int length) { String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random random=new Random(); StringBuffer sb=new StringBuffer(); for(int i=0;i<length;i++) { int number=random.nextInt(62); sb.append(str.charAt(number)); } return sb.toString(); } public void sendShakeHandMsg(String topic,String convid,String appid,String pageid,String carrier,String network,String language,String type,String terminal,String os,String ip,String channel,String referrer) { JSONObject jsonObject=new JSONObject(); jsonObject.put(Constant.FIELD_TYPE, "shakehand"); jsonObject.put(Constant.FIELD_FROM, clientid); jsonObject.put(Constant.FIELD_CONVID, convid); jsonObject.put(Constant.FIELD_APPID, appid); jsonObject.put(Constant.FIELD_PAGEID, pageid); jsonObject.put(Constant.FIELD_ADMIN, 1); JSONObject deviceinfo=new JSONObject(); deviceinfo.put(Constant.FIELD_CARRIER, carrier); deviceinfo.put(Constant.FIELD_NETWORK, network); deviceinfo.put(Constant.FIELD_LANGUAGE, language); deviceinfo.put(Constant.FIELD_TYPE, type); deviceinfo.put(Constant.FIELD_TERMINAL, terminal); deviceinfo.put(Constant.FIELD_OS, os); JSONObject clientinfo=new JSONObject(); clientinfo.put(Constant.FIELD_IP, ip); clientinfo.put(Constant.FIELD_CHANNEL, channel); clientinfo.put(Constant.FIELD_REFERRER, referrer); clientinfo.put(Constant.FIELD_DEVICEINFO, deviceinfo); jsonObject.put(Constant.FIELD_CLIENTINFO, clientinfo); publish( topic,jsonObject.toString()); } public void sendTextMsg(String topic,String convid,String session,String contentinfo) { JSONObject jsonObject=new JSONObject(); jsonObject.put(Constant.FIELD_TYPE, "text"); jsonObject.put(Constant.FIELD_FROM, clientid); jsonObject.put(Constant.FIELD_CONVID, convid); jsonObject.put(Constant.FIELD_SESSION, session); jsonObject.put(Constant.FIELD_TMPINDEX, System.currentTimeMillis()/1000+getRandomString(4)); jsonObject.put(Constant.FIELD_TIME, System.currentTimeMillis()/1000); JSONObject content=new JSONObject(); content.put(Constant.FIELD_CONTENT,contentinfo); jsonObject.put(Constant.FIELD_CONTENT, content); JSONObject extra=new JSONObject(); extra.put(Constant.FIELD_HEADIMGURL, headimgurl); extra.put(Constant.FIELD_NICKNAME, nickname); extra.put(Constant.FIELD_ADMIN, admin); jsonObject.put(Constant.FIELD_EXTRA, extra); publish(topic,jsonObject.toString()); } public void sendImgMsg(String topic,String convid,String session,String url) { JSONObject jsonObject=new JSONObject(); jsonObject.put(Constant.FIELD_TYPE, "image"); jsonObject.put(Constant.FIELD_FROM, clientid); jsonObject.put(Constant.FIELD_CONVID, convid); jsonObject.put(Constant.FIELD_SESSION, session); jsonObject.put(Constant.FIELD_TMPINDEX, System.currentTimeMillis()/1000+getRandomString(4)); jsonObject.put(Constant.FIELD_TIME, System.currentTimeMillis()/1000); JSONObject content=new JSONObject(); content.put(Constant.FIELD_URL,url); jsonObject.put(Constant.FIELD_CONTENT, content); JSONObject extra=new JSONObject(); extra.put(Constant.FIELD_HEADIMGURL, headimgurl); extra.put(Constant.FIELD_NICKNAME, nickname); extra.put(Constant.FIELD_ADMIN, admin); jsonObject.put(Constant.FIELD_EXTRA, extra); publish(topic,jsonObject.toString()); } public JSONObject getSignaling(String convid,String session,String topic) { JSONObject jsonObject=new JSONObject(); jsonObject.put(Constant.FIELD_TYPE, "signaling"); jsonObject.put(Constant.FIELD_FROM, clientid); jsonObject.put(Constant.FIELD_CONVID, convid); jsonObject.put(Constant.FIELD_SESSION, session); jsonObject.put(Constant.FIELD_TMPINDEX, System.currentTimeMillis()/1000+getRandomString(4)); jsonObject.put(Constant.FIELD_TOPIC, topic); jsonObject.put(Constant.FIELD_TIME, System.currentTimeMillis()/1000); return jsonObject; } public void sendVoteOrInput(String convid,String session,String topic,String type,String template,String result) { JSONObject jsonObject=getSignaling(convid,session,topic); JSONObject signaling=new JSONObject(); signaling.put(Constant.FIELD_TYPE, type); signaling.put(Constant.FIELD_TEMPLATE, template); signaling.put("result", result); JSONObject content=new JSONObject(); content.put("signaling", signaling); jsonObject.put(Constant.FIELD_CONTENT, content); publish(topic,jsonObject.toString()); } public void sendEvent(String convid,String session,String topic,String event,String appid,String pageid,String data) { JSONObject jsonObject=getSignaling(convid,session,topic); JSONObject signaling=new JSONObject(); signaling.put(Constant.FIELD_TYPE, "event"); signaling.put(Constant.FIELD_EVENT, event); signaling.put(Constant.FIELD_APPID,appid); signaling.put(Constant.FIELD_PAGEID, pageid); JSONObject dataJson=JSONObject.fromObject(data); signaling.put("data", dataJson); publish(topic,jsonObject.toString()); } public void disconnect() { try { client.disconnect(); } catch (MqttException e) { // TODO Auto-generated catch block e.printStackTrace(); } } class PushCallback implements MqttCallback { @Override public void connectionLost(Throwable arg0) { // TODO Auto-generated method stub System.out.println("连接丢失"); connect(); for(String tmp:topicList) { subscribe(tmp, 2); } } @Override public void deliveryComplete(IMqttDeliveryToken arg0) { // TODO Auto-generated method stub } public void sendAck(String topic,String messagejudge) { System.out.println("aaaaaaaaa"); JSONObject jo=new JSONObject(); try { jo=JSONObject.fromObject(messagejudge); } catch (Exception e) { e.printStackTrace(); } String from=clientid; String tmpindex=jo.getString("tmpindex"); String convid=jo.getString("convid"); String session=from; System.out.println(jo.has("session")); if(jo.has("session")) { session=jo.getString("session"); } System.out.println("bbbbbbbbb"); MqttTopic retopic=client.getTopic(topic); JSONObject jsonObject = new JSONObject(); jsonObject.put(Constant.FIELD_TMPINDEX, tmpindex); jsonObject.put(Constant.FIELD_TYPE, "ack"); jsonObject.put(Constant.FIELD_FROM, clientid); jsonObject.put("to", from); jsonObject.put(Constant.FIELD_SESSION, session); jsonObject.put(Constant.FIELD_CONVID, convid); jsonObject.put(Constant.FIELD_TIME, (int) (System.currentTimeMillis() / 1000)); System.out.println("发送ack确认消息"); try { retopic.publish(jsonObject.toString().getBytes(), 0, false); } catch (MqttException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { System.out.println("接收消息主题 : " + topic); System.out.println("接收消息Qos : " + message.getQos()); System.out.println("接收消息内容 : " + new String(message.getPayload())); //1 抽取事件信令消息 String messagejudge=new String(message.getPayload()); JSONObject jo=new JSONObject(); try { jo=JSONObject.fromObject(messagejudge); } catch (Exception e) { e.printStackTrace(); } String from=jo.getString("from"); String type=jo.getString("type"); if((type.equals("text")||type.equals("image"))&&!from.equals(clientid)) { System.out.println("处理图片和文本消息"); sendAck(topic,messagejudge); String admin=jo.getJSONObject("extra").getString("admin"); if(type.equals("text")){ String content=jo.getJSONObject("content").getString("content"); engynecallback.messageArrived(topic, content,admin); } else if(type.equals("image")){ String url=jo.getJSONObject("content").getString("url"); engynecallback.messageArrived(topic, url,admin); } } if(type.equals("system")&&jo.has("msgCode")) { String msgCode=jo.getString("msgCode"); if(msgCode.equals("1005")) { engynecallback.shakehandSuccess(topic, messagejudge); } else if(msgCode.equals("1007")) { engynecallback.onSystemOffline(topic, msgCode); } } } } public static void main(String[] args) { //EngyneMqtt em=new EngyneMqtt("tcp://dev.engyne.net:1883"); } }