MQTT实现消息推送

SpringBoot实现MQTT消息发送和接收 SpringBoot实现MQTT消息发送和接收。 阅读详情

 

MQTT实现消息推送

 

MQTT实现消息接收(接收消息需实现MqttSimpleCallback接口并实现它的publishArrived方法)必须注册接收消息方法

mqttClient.registerSimpleHandler(simpleCallbackHandler);// 注册接收消息方法

和订阅接主题

mqttClient.subscribe(TOPICS, QOS_VALUES);// 订阅接主题

 

 

服务端:

package com.gmcc.kuchuan.business;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.ibm.mqtt.MqttClient;
import com.ibm.mqtt.MqttException;
import com.ibm.mqtt.MqttSimpleCallback;

/**
 * MQTT消息发送与接收
 * @author Join
 *
 */
public class MqttBroker {
	private final static Log logger = LogFactory.getLog(MqttBroker.class);// 日志对象
	// 连接参数
	private final static String CONNECTION_STRING = "tcp://localhost:9901";
	private final static boolean CLEAN_START = true;
	private final static short KEEP_ALIVE = 30;// 低耗网络,但是又需要及时获取数据,心跳30s
	private final static String CLIENT_ID = "master";// 客户端标识
	private final static int[] QOS_VALUES = { 0, 0, 2, 0 };// 对应主题的消息级别
	private final static String[] TOPICS = { "Test/TestTopics/Topic1",
			"Test/TestTopics/Topic2", "Test/TestTopics/Topic3",
			"client/keepalive" };
	private static MqttBroker instance = new MqttBroker();

	private MqttClient mqttClient;

	/**
	 * 返回实例对象
	 * 
	 * @return
	 */
	public static MqttBroker getInstance() {
		return instance;
	}

	/**
	 * 重新连接服务
	 */
	private void connect() throws MqttException {
		logger.info("connect to mqtt broker.");
		mqttClient = new MqttClient(CONNECTION_STRING);
		logger.info("***********register Simple Handler***********");
		SimpleCallbackHandler simpleCallbackHandler = new SimpleCallbackHandler();
		mqttClient.registerSimpleHandler(simpleCallbackHandler);// 注册接收消息方法
		mqttClient.connect(CLIENT_ID, CLEAN_START, KEEP_ALIVE);
		logger.info("***********subscribe receiver topics***********");
		mqttClient.subscribe(TOPICS, QOS_VALUES);// 订阅接主题

		logger.info("***********CLIENT_ID:" + CLIENT_ID);
		/**
		 * 完成订阅后,可以增加心跳,保持网络通畅,也可以发布自己的消息
		 */
		mqttClient.publish("keepalive", "keepalive".getBytes(), QOS_VALUES[0],
				true);// 增加心跳,保持网络通畅
	}

	/**
	 * 发送消息
	 * 
	 * @param clientId
	 * @param messageId
	 */
	public void sendMessage(String clientId, String message) {
		try {
			if (mqttClient == null || !mqttClient.isConnected()) {
				connect();
			}

			logger.info("send message to " + clientId + ", message is "
					+ message);
			// 发布自己的消息
			mqttClient.publish("GMCC/client/" + clientId, message.getBytes(),
					0, false);
		} catch (MqttException e) {
			logger.error(e.getCause());
			e.printStackTrace();
		}
	}

	/**
	 * 简单回调函数,处理server接收到的主题消息
	 * 
	 * @author Join
	 * 
	 */
	class SimpleCallbackHandler implements MqttSimpleCallback {

		/**
		 * 当客户机和broker意外断开时触发 可以再此处理重新订阅
		 */
		@Override
		public void connectionLost() throws Exception {
			// TODO Auto-generated method stub
			System.out.println("客户机和broker已经断开");
		}

		/**
		 * 客户端订阅消息后,该方法负责回调接收处理消息
		 */
		@Override
		public void publishArrived(String topicName, byte[] payload, int Qos,
				boolean retained) throws Exception {
			// TODO Auto-generated method stub
			System.out.println("订阅主题: " + topicName);
			System.out.println("消息数据: " + new String(payload));
			System.out.println("消息级别(0,1,2): " + Qos);
			System.out.println("是否是实时发送的消息(false=实时,true=服务器上保留的最后消息): "
					+ retained);
		}

	}

	public static void main(String[] args) {
		new MqttBroker().sendMessage("client", "message");
	}
}


 

 

Android客户端:

核心代码:MQTTConnection内部类

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.util.Log;
//此部分项目导包已被删除
import com.ibm.mqtt.IMqttClient;
import com.ibm.mqtt.MqttClient;
import com.ibm.mqtt.MqttException;
import com.ibm.mqtt.MqttPersistence;
import com.ibm.mqtt.MqttPersistenceException;
import com.ibm.mqtt.MqttSimpleCallback;

/* 
 * PushService that does all of the work.
 * Most of the logic is borrowed from KeepAliveService.
 * http://code.google.com/p/android-random/source/browse/trunk/TestKeepAlive/src/org/devtcg/demo/keepalive/KeepAliveService.java?r=219
 */
public class PushService extends Service {
	private MyBinder mBinder = new MyBinder();
	// this is the log tag
	public static final String TAG = "PushService";

	// the IP address, where your MQTT broker is running.
	private static final String MQTT_HOST = "120.197.230.53"; // "209.124.50.174";//
	// the port at which the broker is running.
	private static int MQTT_BROKER_PORT_NUM = 9901;
	// Let's not use the MQTT persistence.
	private static MqttPersistence MQTT_PERSISTENCE = null;
	// We don't need to remember any state between the connections, so we use a
	// clean start.
	private static boolean MQTT_CLEAN_START = true;
	// Let's set the internal keep alive for MQTT to 15 mins. I haven't tested
	// this value much. It could probably be increased.
	private static short MQTT_KEEP_ALIVE = 60 * 15;
	// Set quality of services to 0 (at most once delivery), since we don't want
	// push notifications
	// arrive more than once. However, this means that some messages might get
	// lost (delivery is not guaranteed)
	private static int[] MQTT_QUALITIES_OF_SERVICE = { 0 };
	private static int MQTT_QUALITY_OF_SERVICE = 0;
	// The broker should not retain any messages.
	private static boolean MQTT_RETAINED_PUBLISH = false;

	// MQTT client ID, which is given the broker. In this example, I also use
	// this for the topic header.
	// You can use this to run push notifications for multiple apps with one
	// MQTT broker.
	public static String MQTT_CLIENT_ID = "client";

	// These are the actions for the service (name are descriptive enough)
	public static final String ACTION_START = MQTT_CLIENT_ID + ".START";
	private static final String ACTION_STOP = MQTT_CLIENT_ID + ".STOP";
	private static final String ACTION_KEEPALIVE = MQTT_CLIENT_ID
			+ ".KEEP_ALIVE";
	private static final String ACTION_RECONNECT = MQTT_CLIENT_ID
			+ ".RECONNECT";

	// Connection log for the push service. Good for debugging.
	private ConnectionLog mLog;

	// Connectivity manager to determining, when the phone loses connection
	private ConnectivityManager mConnMan;
	// Notification manager to displaying arrived push notifications
	private NotificationManager mNotifMan;

	// Whether or not the service has been started.
	private boolean mStarted;

	// This the application level keep-alive interval, that is used by the
	// AlarmManager
	// to keep the connection active, even when the device goes to sleep.
	private static final long KEEP_ALIVE_INTERVAL = 1000 * 60 * 28;

	// Retry intervals, when the connection is lost.
	private static final long INITIAL_RETRY_INTERVAL = 1000 * 10;
	private static final long MAXIMUM_RETRY_INTERVAL = 1000 * 60 * 30;

	// Preferences instance
	private SharedPreferences mPrefs;
	// We store in the preferences, whether or not the service has been started
	public static final String PREF_STARTED = "isStarted";
	// We also store the deviceID (target)
	public static final String PREF_DEVICE_ID = "deviceID";
	// We store the last retry interval
	public static final String PREF_RETRY = "retryInterval";

	// Notification title
	public static String NOTIF_TITLE = "client";
	// Notification id
	private static final int NOTIF_CONNECTED = 0;

	// This is the instance of an MQTT connection.
	private MQTTConnection mConnection;
	private long mStartTime;
	boolean mShowFlag = true;// 是否显示通知
	public static Context ctx;
	private boolean mRunFlag = true;// 是否向服务器发送心跳
	Timer mTimer = new Timer();

	// Static method to start the service
	public static void actionStart(Context ctx) {
		Intent i = new Intent(ctx, PushService.class);
		i.setAction(ACTION_START);
		ctx.startService(i);
		PushService.ctx = ctx;
	}

	// Static method to stop the service
	public static void actionStop(Context ctx) {
		Intent i = new Intent(ctx, PushService.class);
		i.setAction(ACTION_STOP);
		ctx.startService(i);
	}

	// Static method to send a keep alive message
	public static void actionPing(Context ctx) {
		Intent i = new Intent(ctx, PushService.class);
		i.setAction(ACTION_KEEPALIVE);
		ctx.startService(i);
	}

	@Override
	public void onCreate() {
		super.onCreate();

		log("Creating service");
		mStartTime = System.currentTimeMillis();

		try {
			mLog = new ConnectionLog();
			Log.i(TAG, "Opened log at " + mLog.getPath());
		} catch (IOException e) {
			Log.e(TAG, "Failed to open log", e);
		}

		// Get instances of preferences, connectivity manager and notification
		// manager
		mPrefs = getSharedPreferences(TAG, MODE_PRIVATE);
		mConnMan = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		mNotifMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		/*
		 * If our process was reaped by the system for any reason we need to
		 * restore our state with merely a call to onCreate. We record the last
		 * "started" value and restore it here if necessary.
		 */
		handleCrashedService();
	}

	// This method does any necessary clean-up need in case the server has been
	// destroyed by the system
	// and then restarted
	private void handleCrashedService() {
		if (wasStarted() == true) {
			log("Handling crashed service...");
			// stop the keep alives
			stopKeepAlives();

			// Do a clean start
			start();
		}
	}

	@Override
	public void onDestroy() {
		log("Service destroyed (started=" + mStarted + ")");

		// Stop the services, if it has been started
		if (mStarted == true) {
			stop();
		}

		try {
			if (mLog != null)
				mLog.close();
		} catch (IOException e) {
		}
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		log("Service started with intent=" + intent);
		if (intent == null) {
			return;
		}
		// Do an appropriate action based on the intent.
		if (intent.getAction().equals(ACTION_STOP) == true) {
			stop();
			stopSelf();
		} else if (intent.getAction().equals(ACTION_START) == true) {
			start();

		} else if (intent.getAction().equals(ACTION_KEEPALIVE) == true) {
			keepAlive();
		} else if (intent.getAction().equals(ACTION_RECONNECT) == true) {
			if (isNetworkAvailable()) {
				reconnectIfNecessary();
			}
		}
	}

	public class MyBinder extends Binder {
		public PushService getService() {
			return PushService.this;
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	// log helper function
	private void log(String message) {
		log(message, null);
	}

	private void log(String message, Throwable e) {
		if (e != null) {
			Log.e(TAG, message, e);

		} else {
			Log.i(TAG, message);
		}

		if (mLog != null) {
			try {
				mLog.println(message);
			} catch (IOException ex) {
			}
		}
	}

	// Reads whether or not the service has been started from the preferences
	private boolean wasStarted() {
		return mPrefs.getBoolean(PREF_STARTED, false);
	}

	// Sets whether or not the services has been started in the preferences.
	private void setStarted(boolean started) {
		mPrefs.edit().putBoolean(PREF_STARTED, started).commit();
		mStarted = started;
	}

	private synchronized void start() {
		log("Starting service...");

		// Do nothing, if the service is already running.
		if (mStarted == true) {
			Log.w(TAG, "Attempt to start connection that is already active");
			return;
		}

		// Establish an MQTT connection

		connect();

		// 向服务器定时发送心跳,一分钟一次
		mRunFlag = true;
		mTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				if (!mRunFlag) {
					// this.cancel();
					// PushService.this.stopSelf();
					return;
				}
				System.out.println("run");
				try {
					if (isNetworkAvailable()) {
						SharedPreferences pref = getSharedPreferences(
								"client", 0);
						String MOBILE_NUM = pref.getString("MOBILE_NUM", "");
						HttpUtil.post(Constants.KEEPALIVE + "&mobile="
								+ MOBILE_NUM + "&online_flag=1");
					}
				} catch (Exception e) {
					e.printStackTrace();
					// TODO: handle exception
				}
			}
		}, 0, 60 * 1000);
		// Register a connectivity listener
		registerReceiver(mConnectivityChanged, new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION));
	}

	private synchronized void stop() {
		// Do nothing, if the service is not running.
		if (mStarted == false) {
			Log.w(TAG, "Attempt to stop connection not active.");
			return;
		}

		// Save stopped state in the preferences
		setStarted(false);

		// Remove the connectivity receiver
		unregisterReceiver(mConnectivityChanged);
		// Any existing reconnect timers should be removed, since we explicitly
		// stopping the service.
		cancelReconnect();

		// Destroy the MQTT connection if there is one
		if (mConnection != null) {
			mConnection.disconnect();
			mConnection = null;
		}
	}

	//
	private synchronized void connect() {
		log("Connecting...");
		// Thread t = new Thread() {
		// @Override
		// public void run() {
		// fetch the device ID from the preferences.
		String deviceID = "GMCC/client/"
				+ mPrefs.getString(PREF_DEVICE_ID, null);
		
		// Create a new connection only if the device id is not NULL
		try {
			mConnection = new MQTTConnection(MQTT_HOST, deviceID);
		} catch (MqttException e) {
			// Schedule a reconnect, if we failed to connect
			log("MqttException: "
					+ (e.getMessage() != null ? e.getMessage() : "NULL"));
			if (isNetworkAvailable()) {
				scheduleReconnect(mStartTime);
			}
		}
		setStarted(true);
		// }
		// };
		// t.start();
		// 向服务器定时发送心跳,一分钟一次
		mRunFlag = true;
	}

	private synchronized void keepAlive() {
		try {
			// Send a keep alive, if there is a connection.
			if (mStarted == true && mConnection != null) {
				mConnection.sendKeepAlive();
			}
		} catch (MqttException e) {
			log("MqttException: "
					+ (e.getMessage() != null ? e.getMessage() : "NULL"), e);

			mConnection.disconnect();
			mConnection = null;
			cancelReconnect();
		}
	}

	// Schedule application level keep-alives using the AlarmManager
	private void startKeepAlives() {
		Intent i = new Intent();
		i.setClass(this, PushService.class);
		i.setAction(ACTION_KEEPALIVE);
		PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
		AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
		alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
				System.currentTimeMillis() + KEEP_ALIVE_INTERVAL,
				KEEP_ALIVE_INTERVAL, pi);
	}

	// Remove all scheduled keep alives
	private void stopKeepAlives() {
		Intent i = new Intent();
		i.setClass(this, PushService.class);
		i.setAction(ACTION_KEEPALIVE);
		PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
		AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
		alarmMgr.cancel(pi);
	}

	// We schedule a reconnect based on the starttime of the service
	public void scheduleReconnect(long startTime) {
		// the last keep-alive interval
		long interval = mPrefs.getLong(PREF_RETRY, INITIAL_RETRY_INTERVAL);

		// Calculate the elapsed time since the start
		long now = System.currentTimeMillis();
		long elapsed = now - startTime;

		// Set an appropriate interval based on the elapsed time since start
		if (elapsed < interval) {
			interval = Math.min(interval * 4, MAXIMUM_RETRY_INTERVAL);
		} else {
			interval = INITIAL_RETRY_INTERVAL;
		}

		log("Rescheduling connection in " + interval + "ms.");

		// Save the new internval
		mPrefs.edit().putLong(PREF_RETRY, interval).commit();

		// Schedule a reconnect using the alarm manager.
		Intent i = new Intent();
		i.setClass(this, PushService.class);
		i.setAction(ACTION_RECONNECT);
		PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
		AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
		alarmMgr.set(AlarmManager.RTC_WAKEUP, now + interval, pi);
	}

	// Remove the scheduled reconnect
	public void cancelReconnect() {
		Intent i = new Intent();
		i.setClass(PushService.this, PushService.class);
		i.setAction(ACTION_RECONNECT);
		PendingIntent pi = PendingIntent.getService(PushService.this, 0, i, 0);
		AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
		alarmMgr.cancel(pi);
	}

	private synchronized void reconnectIfNecessary() {
		log("mStarted" + mStarted);
		log("mConnection" + mConnection);
		if (mStarted == true && mConnection == null) {
			log("Reconnecting...");
			connect();
		}
	}

	// This receiver listeners for network changes and updates the MQTT
	// connection
	// accordingly
	private BroadcastReceiver mConnectivityChanged = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, final Intent intent) {
			// Get network info
			// Thread mReconnect = new Thread(){
			// public void run() {
			NetworkInfo info = (NetworkInfo) intent
					.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
			// Is there connectivity?
			boolean hasConnectivity = (info != null && info.isConnected()) ? true
					: false;

			log("Connectivity changed: connected=" + hasConnectivity);

			if (hasConnectivity) {
				reconnectIfNecessary();
			} else if (mConnection != null) {
				// Thread cancelConn = new Thread(){
				// public void run() {
				// // if there no connectivity, make sure MQTT connection is
				// destroyed
				log("cancelReconnect");
				mConnection.disconnect();
				mConnection = null;
				log("cancelReconnect" + mConnection);
				cancelReconnect();
				// }
				// };
				// cancelConn.start();
			}
			// };
			//
			// };
			// mReconnect.start();
		}
	};

	// Display the topbar notification
	private void showNotification(String text, Request request) {

		Notification n = new Notification();
		n.flags |= Notification.FLAG_SHOW_LIGHTS;
		n.flags |= Notification.FLAG_AUTO_CANCEL;
		n.defaults = Notification.DEFAULT_ALL;
		n.icon = R.drawable.ico;
		n.when = System.currentTimeMillis();
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putSerializable("request", request);
		bundle.putString("currentTab", "1");
		intent.putExtras(bundle);
		intent.setClass(this, MainActivity.class);
		intent.setAction(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		// Simply open the parent activity
		PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);

		// Change the name of the notification here
		n.setLatestEventInfo(this, NOTIF_TITLE, text, pi);
		mNotifMan.notify(NOTIF_CONNECTED, n);
	}

	// Check if we are online
	private boolean isNetworkAvailable() {
		NetworkInfo info = mConnMan.getActiveNetworkInfo();
		if (info == null) {
			return false;
		}
		return info.isConnected();
	}

	// This inner class is a wrapper on top of MQTT client.
	private class MQTTConnection implements MqttSimpleCallback {
		IMqttClient mqttClient = null;

		// Creates a new connection given the broker address and initial topic
		public MQTTConnection(String brokerHostName, String initTopic)
				throws MqttException {
			// Create connection spec
			String mqttConnSpec = "tcp://" + brokerHostName + "@"
					+ MQTT_BROKER_PORT_NUM;
			// Create the client and connect
			mqttClient = MqttClient.createMqttClient(mqttConnSpec,
					MQTT_PERSISTENCE);
			String clientID = MQTT_CLIENT_ID + "/"
					+ mPrefs.getString(PREF_DEVICE_ID, "");
			Log.d(TAG, "mqttConnSpec:" + mqttConnSpec + "  clientID:"
					+ clientID);
			mqttClient.connect(clientID, MQTT_CLEAN_START, MQTT_KEEP_ALIVE);

			// register this client app has being able to receive messages
			mqttClient.registerSimpleHandler(this);

			// Subscribe to an initial topic, which is combination of client ID
			// and device ID.
			// initTopic = MQTT_CLIENT_ID + "/" + initTopic;
			subscribeToTopic(initTopic);

			log("Connection established to " + brokerHostName + " on topic "
					+ initTopic);

			// Save start time
			mStartTime = System.currentTimeMillis();
			// Star the keep-alives
			startKeepAlives();
		}

		// Disconnect
		public void disconnect() {
			// try {
			stopKeepAlives();
			log("stopKeepAlives");
			Thread t = new Thread() {
				public void run() {
					try {
						mqttClient.disconnect();
						log("mqttClient.disconnect();");
					} catch (MqttPersistenceException e) {
						log("MqttException"
								+ (e.getMessage() != null ? e.getMessage()
										: " NULL"), e);
					}
				};
			};
			t.start();
			// } catch (MqttPersistenceException e) {
			// log("MqttException"
			// + (e.getMessage() != null ? e.getMessage() : " NULL"),
			// e);
			// }
		}

		/*
		 * Send a request to the message broker to be sent messages published
		 * with the specified topic name. Wildcards are allowed.
		 */
		private void subscribeToTopic(String topicName) throws MqttException {

			if ((mqttClient == null) || (mqttClient.isConnected() == false)) {
				// quick sanity check - don't try and subscribe if we don't have
				// a connection
				log("Connection error" + "No connection");
			} else {
				String[] topics = { topicName };
				mqttClient.subscribe(topics, MQTT_QUALITIES_OF_SERVICE);
			}
		}

		/*
		 * Sends a message to the message broker, requesting that it be
		 * published to the specified topic.
		 */
		private void publishToTopic(String topicName, String message)
				throws MqttException {
			if ((mqttClient == null) || (mqttClient.isConnected() == false)) {
				// quick sanity check - don't try and publish if we don't have
				// a connection
				log("No connection to public to");
			} else {
				mqttClient.publish(topicName, message.getBytes(),
						MQTT_QUALITY_OF_SERVICE, MQTT_RETAINED_PUBLISH);
			}
		}

		/*
		 * Called if the application loses it's connection to the message
		 * broker.
		 */
		public void connectionLost() throws Exception {
			log("Loss of connection" + "connection downed");
			stopKeepAlives();
			// 取消定时发送心跳
			mRunFlag = false;
			// 向服务器发送请求,更改在线状态
			// SharedPreferences pref = getSharedPreferences("client",0);
			// String MOBILE_NUM=pref.getString("MOBILE_NUM", "");
			// HttpUtil.post(Constants.KEEPALIVE + "&mobile="
			// + MOBILE_NUM+"&online_flag=0");
			// null itself
			mConnection = null;
			if (isNetworkAvailable() == true) {
				reconnectIfNecessary();
			}
		}

		/*
		 * Called when we receive a message from the message broker.
		 */
		public void publishArrived(String topicName, byte[] payload, int qos,
				boolean retained) throws MqttException {
			// Show a notification
			// synchronized (lock) {
			String s = new String(payload);
			Request request = null;
			try {// 解析服务端推送过来的消息
				request = XmlPaserTool.getMessage(new ByteArrayInputStream(s
						.getBytes()));
				// request=Constants.request;
			} catch (Exception e) {
				e.printStackTrace();
			}
			final Request mRequest = request;
			DownloadInfo down = new DownloadInfo(mRequest);
			down.setDownLoad(down);
			downloadInfos.add(down);
			sendUpdateBroast();
			down.start();
			showNotification("您有一条新的消息!", mRequest);
			Log.d(PushService.TAG, s);
			Log.d(PushService.TAG, mRequest.getMessageId());
			// 再向服务端推送消息
			new AdvancedCallbackHandler().sendMessage(MQTT_CLIENT_ID
					+ "/keepalive", "***********send message**********");
		}

		public void sendKeepAlive() throws MqttException {
			log("Sending keep alive");
			// publish to a keep-alive topic
			publishToTopic(MQTT_CLIENT_ID + "/keepalive",
					mPrefs.getString(PREF_DEVICE_ID, ""));
		}
	}

	class AdvancedCallbackHandler {
		IMqttClient mqttClient = null;
		public final int[] QOS_VALUES = { 0, 0, 2, 0 };// 对应主题的消息级别

		/**
		 * 重新连接服务
		 */
		private void connect() throws MqttException {
			String mqttConnSpec = "tcp://" + MQTT_HOST + "@"
					+ MQTT_BROKER_PORT_NUM;
			// Create the client and connect
			mqttClient = MqttClient.createMqttClient(mqttConnSpec,
					MQTT_PERSISTENCE);
			String clientID = MQTT_CLIENT_ID + "/"
					+ mPrefs.getString(PREF_DEVICE_ID, "");
			mqttClient.connect(clientID, MQTT_CLEAN_START, MQTT_KEEP_ALIVE);
			Log.d(TAG, "连接服务器,推送消息");
			Log.d(TAG, "**mqttConnSpec:" + mqttConnSpec + "  clientID:"
					+ clientID);
			Log.d(TAG, MQTT_CLIENT_ID + "/keepalive");
			// 增加心跳,保持网络通畅
			mqttClient.publish(MQTT_CLIENT_ID + "/keepalive",
					"keepalive".getBytes(), QOS_VALUES[0], true);
		}

		/**
		 * 发送消息
		 * 
		 * @param clientId
		 * @param messageId
		 */
		public void sendMessage(String clientId, String message) {
			try {
				if (mqttClient == null || !mqttClient.isConnected()) {
					connect();
				}

				Log.d(TAG, "send message to " + clientId + ", message is "
						+ message);
				// 发布自己的消息
				// mqttClient.publish(MQTT_CLIENT_ID + "/keepalive",
				// message.getBytes(), 0, false);
				mqttClient.publish(MQTT_CLIENT_ID + "/keepalive",
						message.getBytes(), 0, false);
			} catch (MqttException e) {
				Log.d(TAG, e.getCause() + "");
				e.printStackTrace();
			}
		}
	}

	public String getPeople(String phone_number) {
		String name = "";
		String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER };
		Log.d(TAG, "getPeople ---------");
		// 将自己添加到 msPeers 中
		Cursor cursor = this.getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
				projection, // Which columns to return.
				ContactsContract.CommonDataKinds.Phone.NUMBER + " = '"
						+ phone_number + "'", // WHERE clause.
				null, // WHERE clause value substitution
				null); // Sort order.

		if (cursor == null) {
			Log.d(TAG, "getPeople null");
			return "";
		}
		Log.d(TAG, "getPeople cursor.getCount() = " + cursor.getCount());
		if (cursor.getCount() > 0) {
			cursor.moveToPosition(0);

			// 取得联系人名字
			int nameFieldColumnIndex = cursor
					.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
			name = cursor.getString(nameFieldColumnIndex);
			Log.i("Contacts", "" + name + " .... " + nameFieldColumnIndex); // 这里提示
																			// force
																			// close
			System.out.println("联系人姓名:" + name);
			return name;
		}
		return phone_number;
	}

	public void sendUpdateBroast() {
		Intent intent = new Intent();
		intent.setAction("update");
		sendBroadcast(intent);
	}

	public void sendUpdateFinishBroast() {
		Intent intent = new Intent();
		intent.setAction("updateFinishList");
		sendBroadcast(intent);
	}

	public class DownloadInfo extends Thread {
		boolean runflag = true;
		Request mRequest;
		public float progress;
		public MessageBean bean = null;
		DownloadInfo download = null;
		MessageDetailDao dao = new MessageDetailDao(
				PushService.this.getApplicationContext());

		public synchronized void stopthread() {
			runflag = false;
		}

		public synchronized boolean getrunflag() {
			return runflag;
		}

		DownloadInfo(Request mRequest) {
			this.mRequest = mRequest;

		}

		public void setDownLoad(DownloadInfo download) {
			this.download = download;
		}

		@Override
		public void run() {
			try {

				File dir = new File(Constants.DOWNLOAD_PATH);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				String filePath = Constants.DOWNLOAD_PATH
						+ mRequest.getMessageId() + "." + mRequest.getExt();
				bean = new MessageBean();
				bean.setPath(filePath);
				bean.setStatus(0);
				bean.setDate(mRequest.getTimestamp());
				bean.setLayoutID(R.layout.list_say_he_item);
				bean.setPhotoID(R.drawable.receive_ico);
				bean.setMessage_key(mRequest.getMessageId());
				bean.setPhone_number(mRequest.getReceiver());
				bean.setAction(1);
				String name = getPeople(mRequest.getSender());
				bean.setName(name);
				bean.setFileType(Integer.parseInt(mRequest.getCommand()));
				if (mRequest.getCommand().equals(Request.TYPE_MUSIC)) {
					bean.setMsgIco(R.drawable.music_temp);
					bean.setText(name + "给你发送了音乐");
					mRequest.setBody(Base64.encodeToString(bean.getText()
							.getBytes(), Base64.DEFAULT));
				} else if (mRequest.getCommand().equals(Request.TYPE_CARD)) {
					bean.setMsgIco(R.drawable.card_temp);
					bean.setText(new String(Base64.decode(mRequest.getBody(),
							Base64.DEFAULT)));
					mRequest.setBody(Base64.encodeToString(bean.getText()
							.getBytes(), Base64.DEFAULT));
				} else if (mRequest.getCommand().equals(Request.TYPE_LBS)) {
					bean.setMsgIco(R.drawable.address_temp);
					bean.setText(new String(Base64.decode(mRequest.getBody(),
							Base64.DEFAULT)));
					mRequest.setBody(Base64.encodeToString(bean.getText()
							.getBytes(), Base64.DEFAULT));
				} else if (mRequest.getCommand().equals(Request.TYPE_PHOTO)) {
					bean.setText(name + "向你发送了照片");
					bean.setMsgIco(-1);
				} else if (mRequest.getCommand().equals(Request.TYPE_PIC)) {
					bean.setText(name + "向你发送了图片");
					bean.setMsgIco(-1);
				} else if (mRequest.getCommand().equals(Request.TYPE_SMS)) {
					bean.setFileType(0);
				}

				if (!mRequest.getCommand().equals(Request.TYPE_CARD)
						&& !mRequest.getCommand().equals(Request.TYPE_SMS)) {
					String path = Constants.FILE_DOWNLOAD_URL
							+ mRequest.getMessageId();
					URL url = new URL(path);
					HttpURLConnection hurlconn = (HttpURLConnection) url
							.openConnection();// 基于HTTP协议的连接对象
					hurlconn.setConnectTimeout(5000);// 请求超时时间 5s
					hurlconn.setRequestMethod("GET");// 请求方式
					hurlconn.connect();
					long fileSize = hurlconn.getContentLength();
					InputStream instream = hurlconn.getInputStream();
					byte[] buffer = new byte[1024];
					int len = 0;
					int number = 0;
					RandomAccessFile rasf = new RandomAccessFile(filePath,
							"rwd");
					while ((len = instream.read(buffer)) != -1) {// 开始下载文件
						if (getrunflag() && progress < 100) {
							rasf.seek(number);
							number += len;
							rasf.write(buffer, 0, len);
							progress = (((float) number) / fileSize) * 100;
							// 发送广播,修改进度条进度
							sendUpdateBroast();
						} else {
							this.interrupt();
							if (number != fileSize) {// 取消下载,将已经缓存的未下载完成的文件删除
								File file = new File(filePath);
								if (file.exists())
									file.delete();
							}
							PushService.downloadInfos.remove(download);
							sendUpdateBroast();
							return;
						}
					}
					instream.close();
					PushService.downloadInfos.remove(download);
					sendUpdateBroast();
				} else {// 收到消息,将信息保存到数据库

					PushService.downloadInfos.remove(download);
					sendUpdateBroast();
				}
				// 将文件信息保存到数据库
				dao.create(bean);
				sendUpdateFinishBroast();

			} catch (Exception e) {
				PushService.downloadInfos.remove(download);
				sendUpdateBroast();
				e.printStackTrace();
			}
		}
	}

	public static ArrayList<DownloadInfo> downloadInfos = new ArrayList<DownloadInfo>();

	public ArrayList<DownloadInfo> getDownloadInfos() {
		return PushService.downloadInfos;
	}

	public void setDownloadInfos(ArrayList<DownloadInfo> downloadInfos) {
		PushService.downloadInfos = downloadInfos;
	}
}


 ps:

接收者必须订阅发送者的TOPICS才能收到消息

 






        
MQTT C Client实现消息推送(入门指南) MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是IBM开发的一个即时通讯协议,通过MQTT协议,目前已经扩展出了数十个MQTT服务器端程序,可以通过PHP,JAVA,Python,C,C#等系统语言来向MQTT发送相关消息。随着移动互联网的发展,MQTT由于开放源代码,耗电量小等特点,将会在移动消息推送领域会有更多的贡献。 阅读详情

相关推荐

基于Mqtt协议Paho项目实现Android消息推送

基于Mqtt协议Paho项目实现Android消息推送 服务端的部署 客户端的实现 演示Gif

linghuanyun的博客 7748

MQTT协议笔记之订阅

记忆不太好的时候,只能翻看以前的文章/笔记重新温习一遍,但找不到MQTT协议有关订阅部分的描述,好不容易从Evernote中找到贴出来,这样整个MQTT协议笔记,就比较齐全了。 SUBSCRIBE 一般来讲,客户端在成功建立TCP连接之后,发送CONNECT消息,在得到服务器端授权允许建立彼此连接的CONNACK消息之后,客户端会发送SUBSCRIBE消息,订阅感兴趣的Topic主题列

~笑对人生~ 1624

非线性功率放大器对QAM传输BER性能的影响及补偿

1、线性功率放大器对传输性能的影响 为表述非线性功率放大器对传输性能的影响,以Saleh模型进行观察。具体来说,在QAM调制器之后添加一个非线性模块,使调制后的波形经历AM / AM和AM / PM转换。 在Saleh模型中,转换用四个参数表示,即AM / AM转换为????a和????a,AM / PM转换为????p和????p。 在Saleh模型中,AM / AM和AM / PM方程以输入电压u的大小表示为: 式中,FAM / AM是AM / AM转换的输出电压与输入电压的关系,而FAM

太阳帅帅的博客 2080

Java MQTT 完整实战指南:接收消息与处理详解

通过以上代码,你可以快速实现一个简单的Java MQTT 消息接收器。只需替换你的服务器地址、用户名和密码,即可接收来自指定主题的消息。下一步可以做什么?添加消息持久化功能,将接收到的消息保存到数据库。实现多主题监听,订阅多个 MQTT 主题。结合前端展示,实时可视化消息内容。

Takumilove的博客 3784

不止于使能:用汇川PLC功能块封装,实现伺服轴状态管理与安全逻辑

本文深入探讨了汇川PLC功能块封装在伺服轴控中的应用,详细介绍了如何通过高级封装技术实现伺服轴的状态管理与安全逻辑。文章涵盖了从基础使能到全生命周期监控的进化,多轴协同的实例化管理策略,以及安全逻辑的防御性编程技巧,为工业自动化领域的工程师提供了实用的解决方案和最佳实践。

weixin_28684825的博客 271

别再只测电压了!用STM32G474的ADC玩点花的:过采样提升精度与多通道扫描实战

本文深入探讨了STM32G474系列单片机的ADC高级应用,包括硬件过采样技术实现16位精度和多通道扫描结合DMA的自动数据采集方案。通过详细的配置步骤和实战案例,帮助开发者突破传统电压测量局限,提升信号采集精度和系统效率,适用于工业监控、医疗设备等高精度应用场景。

weixin_42647395的博客 238

springboot集成MQTT实现消息接收

springboot集成Mqtt消息接收

不知道说什么的博客 1830

CCS环境下ADC采样波形的实时可视化调试技巧

本文详细介绍了在CCS环境下实现ADC采样波形实时可视化的调试技巧。通过数组缓存优化、多通道同步显示和波形测量工具的高级用法,帮助开发者高效调试嵌入式系统中的ADC采样问题,提升信号分析的准确性和效率。

weixin_33712987的博客 419

MQTT接收消息到发送消息全配置

MQTT发送topic消息,接收topic消息业务处理

xhzf88的博客 1857

光伏发电预测(LSTM、CNN_LSTM和XGBoost回归模型,Python代码)

一旦结果与预测差距较大,可能存在光伏系统的问题,需要找出原因,然后采取适当措施来修复光伏系统并做出更好的决策。例如,根据准确的预测,光伏系统运营商可以平衡电力消耗,并将多余的电力储备用于紧急情况。然而,光伏系统的发电量估算是一个挑战,因为光伏系统的发电量受到天气条件的极大影响。整个项目文件夹(第一个文件夹为xgboost模型相关的包文件,xg.py是xgboost模型英文注释版本,xg_chinese.py是xgboost模型中文注释版本)表示空气的温度,通常以摄氏度(°C)或华氏度(°F)为单位。

2301_79699110的博客 3032

CAPL编程入门:从零开始掌握汽车通信脚本语言

本文详细介绍了CAPL编程的基础知识,从开发环境搭建到核心语法精要,再到总线通信实战和高级调试技巧。CAPL作为汽车通信脚本语言,专为CAN、LIN等网络协议设计,帮助工程师高效完成车载网络测试。通过实战案例和性能优化建议,读者可以快速掌握CAPL编程技能。

s1t2u3的博客 978

酷炫MQTT实现消息推送

首先在实现本功能之前我们需要储备一下预备知识,大家可以看我的前两篇文章以及官网,了解MQTT的基本常识: MQTT入门篇 MQTT服务器Mosquitto安装及使用 MQTT官网 在步入正题之前先给大家发放个福利,介绍一款MQTT插件:MQTTLens 。 MQTTLens插件的使用 MQTTLens 1.安装:点击链接进行安装。 2.输入以下三个信息: connection

李彬博客专栏 3万+

从解压到编译:手把手带你用TeXstudio搞定第一篇ACM LaTeX论文

本文详细指导如何使用TeXstudio从解压ACM LaTeX模板到成功编译第一篇学术论文的全过程。涵盖环境准备、模板配置、TeXstudio设置及常见问题排查,特别针对ACM会议论文格式要求,帮助学术新人快速掌握LaTeX写作技巧。

weixin_30655569的博客 254

采用MQTT协议实现Android消息推送1

[原]采用MQTT协议实现Android消息推送 对于消息推送,一开始还真不知道什么方式比较好,一头雾水,现在回顾总结下资料。 http://zheye.org/asks/4d99a1aafd503c41d700000a 通过上面者也里面的回复,得到一些信息。 1.官方的C2DM,但是只支持android2.2及以上平台的,而且使用的google的服务器。 对于google服务器

Java程序员命运之改变 759

node: /lib64/libstdc++.so.6: version `CXXABI_1.3.11‘ not found (required by node) 解决方案

本文主要介绍了node: /lib64/libstdc++.so.6: version `CXXABI_1.3.11’ not found (required by node) ,希望能对使用nodejs的同学们有所帮助。 文章目录 1. 问题描述 2. 解决方案

weixin_43178406的博客 1万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

采用MQTT协议实现Android消息推送

原文:http://www.cnblogs.com/glony/articles/2308165.html [原]采用MQTT协议实现Android消息推送 对于消息推送,一开始还真不知道什么方式比较好,一头雾水,现在回顾总结下资料。 http://zheye.org/asks/4d99a1aafd503c41d700000a 通过上面者也里面的回复,得

xuyuegang的专栏 1374

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

MQTT+ApolloServer实现Android的消息推送功能

应用背景 最近,领导让研究android系统的应用开发,于是就开始研究数据库访问+消息推送+实时视频播放等基本应用,下面主要是android消息推送功能的研究。PS:大家有问题可以随时私信我,共同学习。 消息的推送就是从服务器端向移动终端发送连接请求,传输特定的信息。例如一些新闻客户端,每隔一段时间都会受到一条或者多条通知(Notification),这就是从服务器端传过来的推送消息。

纸上得来终觉浅,绝知此事要躬行 8216

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

SpringBoot2.0集成MQTT消息推送功能实现

如果不指定,则使用默认配置的主题。这几天在弄后端管理系统向指定的Android客户端推送消息的功能模块,查阅了网上很多博客介绍的许多方式,最终选择基于MQTT协议来实现,MQTT是一个轻量级的消息发布/订阅协议,它是实现基于手机客户端的消息推送服务器的理想解决方案。最后,写个接口类测试下功能,用Postman调用sendMqtt.do接口,往hello主题发送消息,用MQTTLens订阅hello主题,从下面截图,可以看出可以正常往MQTT服务发送消息了,而且可以订阅到。第三,配置MQTT消息推送配置类,

群群的博客 1090

rabbitmq作为mqtt服务器实现websocket消息推送给浏览器

rabbitmq的RabbitMQ Web MQTT插件可以用来支持将rabbitmq作为MQTT协议的服务器,而websocket支持mqtt协议通信实现消息推送。因为我们目前使用rabbitmq,所以采用其作为ws的服务端(原来有过activemq的做法,其原生也支持MQTT协议)。 首先安装RabbitMQ Web MQTT插件,如下: rabbitmq-plugins enable...

weixin_30709809的博客 2231

mqtt消息推送 java_MQTT+ActiveMQ实现消息推送(服务器端java实现)

上一篇文章已经介绍了mqtt+activemq实现消息推送移动端的实现,也介绍了利用自带的web console进行消息发布的方法。但是在具体的项目应用中,当我们将需要将该消息推送模块嵌入到一个后台管理系统当中,我们就需要在web端来访问activeMQ来进行消息的发布。同样用的是org.eclipse.paho.client.mqttv3包,相信看过上一篇文章已经有了一定的了解,直接来看代码@C...

weixin_28908491的博客 924
上一篇: 获取sim卡运营商
下一篇: [SVN错误]svn already locked
join_wangzi
博客等级 码龄15年 37粉丝 14原创
评论 117
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值