mqtt 怎么让苹果用相同的idclintid同时登陆

问题描述:在使用MQTT.fx软件时,两台不同的电脑连接同个服务器地址报以下错误问题原因:Clien ID相同,两台设备使用了相同的ID解决方法:在设置中修改Client ID,使两台设备ID值不同
MQTT调试工具 mqtt.fx的使用
MQTT再学习 -- 搭建MQTT服务器及测试
用mqtt.fx 和 wireshark 深入学习MQTT 协议
最近做了一个Mqtt消息推送,和大家分享分享心得,以防以后搞忘了,新人第一次写博客,大神勿喷。
没有更多推荐了,博客分类:
使用activeMQ进行android推送
activeMQ下载地址:http://activemq.apache.org/download.html
下载后是一个压缩包:apache-activemq-5.9.0-bin.zip
解压缩,进入apache-activemq-5.9.0-bin\apache-activemq-5.9.0\bin,双击activemq.bat,即可启动activeMQ服务 启动之后: android客户端推送采用mqtt(paho-mqtt-client-1.0.1.jar),依赖包见附件
但是为了测试,我写了一个swing图形界面,充当手机客户端,依赖的jar包仍然是paho-mqtt-client-1.0.1.jar.界面如下:
使用方法:点击[启动]按钮,开始接收推送消息 对应的主类是:MqttSwing,用于接收推送消息.
我还写了一个发送推送消息的swing图形界面,充当推送后管系统,界面如下:
使用方法:点击[连接]按钮,才可以发送推送消息 对应的主类:PusherApp,用于发送推送消息.
核心代码介绍如下.
客户端连接activeMQ,建立连接(只有建立连接,才能接收到推送消息)
方法名:connect,做了两件事:(1)建立连接;(2)订阅主题(topic)
* 客户端和activeMQ服务器建立连接
* @param BROKER_URL
* @param clientId : 用于标识客户端,相当于ios中的device token
* @param TOPIC
* @param isCleanSession :false--可以接受离线消息;
* @return 是否启动成功
private boolean connect(String BROKER_URL,String clientId,String TOPIC,boolean isCleanSession){
ComponentUtil.appendResult(resultTextPane, "connect time:"+TimeHWUtil.getCurrentMiniuteSecond(), true);
mqttClient = new MqttClient(BROKER_URL, clientId, new MemoryPersistence());
MqttConnectOptions options= new MqttConnectOptions();
options.setCleanSession(isCleanSession);//mqtt receive offline message
ComponentUtil.appendResult(resultTextPane, "isCleanSession:"+isCleanSession, true);
options.setKeepAliveInterval(30);
//推送回调类,在此类中处理消息,用于消息监听
mqttClient.setCallback(new MyCallBack(MqttSwing.this));
boolean isSuccess=
mqttClient.connect(options);//CLIENT ID CAN NOT BE SAME
isSuccess=
} catch (Exception e) {
if(isPrintException){
e.printStackTrace();
if(!isSuccess){
String message="连接失败,请检查client id是否重复了 或者activeMQ是否启动";
ComponentUtil.appendResult(resultTextPane, message, true);
GUIUtil23.warningDialog(message);
//Subscribe to topics
mqttClient.subscribe(new String[]{TOPIC,clientId});
System.out.println("topic:"+TOPIC+",
"+(clientId));
ComponentUtil.appendResult(resultTextPane, "TOPIC:"+TOPIC+",
"+(clientId), true);
} catch (MqttException e) {
if(isPrintException){
e.printStackTrace();}
GUIUtil23.errorDialog(e.getMessage());
推送消息到来时的回调类:MyCallBack
package com.mqtt.hw.
import org.apache.commons.lang.StringEscapeU
import org.eclipse.paho.client.mqttv3.MqttC
import org.eclipse.paho.client.mqttv3.MqttDeliveryT
import org.eclipse.paho.client.mqttv3.MqttM
import org.eclipse.paho.client.mqttv3.MqttT
import com.mqtt.hw.MqttS
import com.time.util.TimeHWU
public class MyCallBack implements MqttCallback {
private MqttSwing mqttS
public MyCallBack(MqttSwing mqttSwing) {
this.mqttSwing = mqttS
public void connectionLost(Throwable cause) {
public void messageArrived(MqttTopic topic, MqttMessage message)
throws Exception {
System.out.println("messageArrived...."+TimeHWUtil.getCurrentMiniuteSecond());
String messageStr=StringEscapeUtils.unescapeHtml(new String(message.getPayload()));
System.out.println("message:"+messageStr);
this.mqttSwing.receiveMessage(messageStr);
//使窗口处于激活状态
public void deliveryComplete(MqttDeliveryToken token) {
推送者与activeMQ建立连接:
* 初始化connection和session
* @throws Exception
private void init(/* String mqIp,boolean transacted */) throws Exception {
if (!DialogUtil.verifyTFEmpty(serverIpTextField, "服务器ip")) {
String transactedStr = transactedTextField.getText();
boolean transacted =
if (ValueWidget.isNullOrEmpty(transactedStr)) {
transacted =
transacted = Boolean.parseBoolean(transactedStr);
String message = "transacted:" +
ComponentUtil.appendResult(resultTextArea, message, true);
System.out.println(message);
String brokerUrl = String.format(BROKER_URL,
serverIpTextField.getText());
// 创建链接工厂
TopicConnectionFactory factory = new ActiveMQConnectionFactory(
ActiveMQConnection.DEFAULT_USER,
ActiveMQConnection.DEFAULT_PASSWORD, brokerUrl);
ComponentUtil.appendResult(resultTextArea, "url:" + brokerUrl, true);
// 通过工厂创建一个连接
connection = factory.createTopicConnection();
// 启动连接
connection.start();
ComponentUtil.appendResult(resultTextArea, "启动connection 成功", true);
// 创建一个session会话 transacted
session = connection.createTopicSession(
transacted /* Boolean.FALSE */, Session.AUTO_ACKNOWLEDGE);
项目源代码见附件mqtt_swing.zip
手机android客户端(测试推送)见附件android-mqtt-push-master.zip
详细配置参阅附件mqtt推送详解.zip
依赖的jar包
io0007-find_progess-0.0.8.4-SNAPSHOT.jar
io0007-find_progess-0.0.8.4-SNAPSHOT-sources.jar
---号更新--
https://github.com/liuyu520/mqtt_client_swing.git
https://github.com/liuyu520/io0007
下载次数: 900
(117.4 KB)
下载次数: 533
下载次数: 949
(247.9 KB)
下载次数: 787
(463.9 KB)
下载次数: 291
(256.3 KB)
下载次数: 361
(193.7 KB)
下载次数: 259
浏览 35927
你好,请问有IOS和推送后台(服务器端)的资料吗?最新代码:https://github.com/liuyu520/mqtt_client_swing.git
运行你的那个 的,提示错误: 找不到或无法加载主类 com.mqtt.hw.MqttClientSwing,新手 求教& qq&
谢谢最新代码:https://github.com/liuyu520/mqtt_client_swing.git
如果客户端下线了,上线后,消息还会推送给他吗,这个有设置吗最新代码:https://github.com/liuyu520/mqtt_client_swing.git
如果客户端下线了,上线后,消息还会推送给他吗,这个有设置吗我们也是基于MQTT协议实现的实时通信系统,消息推送只是我们其中的一项产品服务。 实现Android推送方面,客户端在集成我们的 Android SDK后,服务端便可通过 SDK 或使用 RESTful API,向 Android 客户端发消息。为了保证消息的实时性,我们Android SDK 会启动一个后台的 Service,创建并保持到云巴服务器的长连接,从而保证了消息推送的实时性。同样为了保证消息能够被送达,我们 SDK 支持 离线消息 的功能,可保证消息送达客户端。也就是说,在推送消息时,如果客户端当前不在线,消息将暂存在云巴服务器上(多达 50 条,长达 15 天)。 当客户端上线并成功连接到云巴的服务器后,服务器会把离线消息推送给该客户端。客户端成功接收后,服务器才会删除保存的离线消息。iOS推送同理,除此以外,我们的 SDK 集成了 APNs,这样开发者就无需开发与 APNs 对接的模块,也不必自己负责 Device Token 的更新。
import com.swing.component.AssistPopupTextPane 没找到这个包呢,能否发一份最新完整的给我这个类在附件的io0007-find_progess-0.0.8.4-SNAPSHOT.jar
你好,请问有IOS和推送后台(服务器端)的资料吗?ios 推送资料下载地址:
import com.swing.component.AssistPopupTextPane 没找到这个包呢,能否发一份最新完整的给我http://pan.baidu.com/s/1hqlAekW
浏览: 3461561 次
来自: 北京
这个方法对于子类来说是没效果的
没这么麻烦吧,网上找了一个Holer工具,只需要配置一个Acc ...
Jmeter性能测试从入门到精通(2018年最新)课程观看地址 ...
6ee55ec8ed9fff ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'o Published 21 days ago
MQTT.js is a client library for the
protocol, written
in JavaScript for node.js and the browser.
MQTT.js is an OPEN Open Source Project, see the
section to find out what this means.
Important notes for existing users
v2.0.0 removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending
packets. It also removes all the deprecated functionality in v1.0.0,
mainly mqtt.createConnection and mqtt.Server. From v2.0.0,
subscriptions are restored upon reconnection if clean: true.
v1.x.x is now in LTS, and it will keep being supported as long as
there are v0.8, v0.10 and v0.12 users.
v1.0.0 improves the overall architecture of the project, which is now
split into three components: MQTT.js keeps the Client,
includes the barebone
Connection code for server-side usage, and
includes the protocol parser and generator. The new Client improves
performance by a 30% factor, embeds Websocket support
( is now deprecated), and it has a better
support for QoS 1 and 2. The previous API is still supported but
deprecated, as such, it is not documented in this README.
As a breaking change, the encoding option in the old client is
removed, and now everything is UTF-8 with the exception of the
password in the CONNECT message and payload in the PUBLISH message,
which are Buffer.
Another breaking change is that MQTT.js now defaults to MQTT v3.1.1,
so to support old brokers, please read the .
Installation
npm install mqtt --save
For the sake of simplicity, let's put the subscriber and the publisher in the same file:
var mqtt = require('mqtt')var client
= mqtt.connect('mqtt://test.mosquitto.org') client.on('connect', function () {
client.subscribe('presence')
client.publish('presence', 'Hello mqtt')}) client.on('message', function (topic, message) {
message is Buffer
console.log(message.toString())
client.end()})
Hello mqtt
If you want to run your own MQTT broker, you can use
, and launch it.
You can also use a test instance: test.mosquitto.org and test.mosca.io
are both public.
If you do not want to install a separate broker, you can try using the
to use MQTT.js in the browser see the
Promise support
If you want to use the new
functionality in JavaScript, or just prefer using Promises instead of callbacks,
is a wrapper over MQTT.js which uses promises instead of callbacks when possible.
Command Line Tools
MQTT.js bundles a command to interact with a broker.
In order to have it available on your path, you should install MQTT.js
npm install mqtt -g
Then, on one terminal
mqtt sub -t 'hello' -h 'test.mosquitto.org' -v
On another
mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js'
See mqtt help &command& for the command help.
mqtt.connect([url], options)
Connects to the broker specified by the given url and options and
returns a .
The URL can be on the following protocols: 'mqtt', 'mqtts', 'tcp',
'tls', 'ws', 'wss'. The URL can also be an object as returned by
in that case the two objects are merged, i.e. you can pass a single
object with both the URL and the connect options.
You can also specify a servers options with content: [{ host: 'localhost', port: 1883 }, ... ], in that case that array is iterated
at every connect.
For all MQTT-related options, see the
constructor.
mqtt.Client(streamBuilder, options)
The Client class wraps a client connection to an
MQTT broker over an arbitrary transport method (TCP, TLS,
WebSocket, ecc).
Client automatically handles the following:
Regular server pings
Automatic reconnections
Start publishing before being connected
The arguments are:
streamBuilder is a function that returns a subclass of the Stream class that supports
the connect event. Typically a net.Socket.
options is the client connection options (see: the ). Defaults:
wsOptions: is the WebSocket connection options. Default is {}.
It's specific for WebSockets. For possible options have a look at: .
keepalive: 60 seconds, set to 0 to disable
reschedulePings: reschedule ping messages after sending packets (default true)
clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8)
protocolId: 'MQTT'
protocolVersion: 4
clean: true, set to false to receive QoS 1 and 2 messages while
reconnectPeriod: 1000 milliseconds, interval between two
reconnections
connectTimeout: 30 * 1000 milliseconds, time to wait before a
CONNACK is received
username: the username required by your broker, if any
password: the password required by your broker, if any
incomingStore: a
for the incoming packets
outgoingStore: a
for the outgoing packets
queueQoSZero: if connection is broken, queue outgoing QoS zero messages (default true)
will: a message that will sent by the broker automatically when
the client disconnect badly. The format is:
topic: the topic to publish
payload: the message to publish
qos: the QoS
retain: the retain flag
transformWsUrl : optional (url, options, client) =& url function
For ws/wss protocols only. Can be used to implement signing
urls which upon reconnect can have become expired.
resubscribe : if connection is broken and reconnects,
subscribed topics are automatically subscribed again (default true)
In case mqtts (mqtt over tls) is required, the options object is
passed through to
If you are using a self-signed certificate, pass the rejectUnauthorized: false option.
Beware that you are exposing yourself to man in the middle attacks, so it is a configuration
that is not recommended for production environments.
If you are connecting to a broker that supports only MQTT 3.1 (not
3.1.1 compliant), you should pass these additional options:
protocolId: 'MQIsdp',
protocolVersion: 3}
This is confirmed on RabbitMQ 3.2.4, and on Mosquitto & 1.3. Mosquitto
version 1.3 and 1.4 works fine without those.
Event 'connect'
function (connack) {}
Emitted on successful (re)connection (i.e. connack rc=0).
connack received connack packet. When clean connection option is false and server has a previous session
for clientId connection option, then connack.sessionPresent flag is true. When that is the case,
you may rely on stored session and prefer not to send subscribe commands for the client.
Event 'reconnect'
function () {}
Emitted when a reconnect starts.
Event 'close'
function () {}
Emitted after a disconnection.
Event 'offline'
function () {}
Emitted when the client goes offline.
Event 'error'
function (error) {}
Emitted when the client cannot connect (i.e. connack rc != 0) or when a
parsing error occurs.
Event 'end'
function () {}
Emitted when
is called.
If a callback was passed to mqtt.Client#end(), this event is emitted once the
callback returns.
Event 'message'
function (topic, message, packet) {}
Emitted when the client receives a publish packet
topic topic of the received packet
message payload of the received packet
packet received packet, as defined in
Event 'packetsend'
function (packet) {}
Emitted when the client sends any packet. This includes .published() packets
as well as packets used by MQTT for managing subscriptions and connections
packet received packet, as defined in
Event 'packetreceive'
function (packet) {}
Emitted when the client receives any packet. This includes packets from
subscribed topics as well as packets used by MQTT for managing subscriptions
and connections
packet received packet, as defined in
mqtt.Client#publish(topic, message, [options], [callback])
Publish a message to a topic
topic is the topic to publish to, String
message is the message to publish, Buffer or String
options is the options to publish with, including:
qos QoS level, Number, default 0
retain retain flag, Boolean, default false
dup mark as duplicate flag, Boolean, default false
callback - function (err), fired when the QoS handling completes,
or at the next tick if QoS 0. An error occurs if client is disconnecting.
mqtt.Client#subscribe(topic/topic array/topic object, [options], [callback])
Subscribe to a topic or topics
topic is a String topic to subscribe to or an Array of
topics to subscribe to. It can also be an object, it has as object
keys the topic name and as value the QoS, like {'test1': 0, 'test2': 1}.
MQTT topic wildcard characters are supported (+ - for single level and # - for multi level)
options is the options to subscribe with, including:
qos qos subscription level, default 0
callback - function (err, granted)
callback fired on suback where:
err a subscription error or an error that occurs when client is disconnecting
granted is an array of {topic, qos} where:
topic is a subscribed to topic
qos is the granted qos level on it
mqtt.Client#unsubscribe(topic/topic array, [callback])
Unsubscribe from a topic or topics
topic is a String topic or an array of topics to unsubscribe from
callback - function (err), fired on unsuback. An error occurs if client is disconnecting.
mqtt.Client#end([force], [cb])
Close the client, accepts the following options:
force: passing it to true will close the client right away, without
waiting for the in-flight messages to be acked. This parameter is
cb: will be called when the client is closed. This parameter is
mqtt.Client#removeOutgoingMessage(mid)
Remove a message from the outgoingStore.
The outgoing callback will be called withe Error('Message removed') if the message is removed.
After this function is called, the messageId is released and becomes reusable.
mid: The messageId of the message in the outgoingStore.
mqtt.Client#reconnect()
Connect again using the same options as connect()
mqtt.Client#handleMessage(packet, callback)
Handle messages with backpressure support, one at a time.
Override at will, but always call callback, or the client
will hang.
mqtt.Client#connected
Boolean : set to true if the client is connected. false otherwise.
mqtt.Client#getLastMessageId()
Number : get last message id. This is for sent messages only.
mqtt.Client#reconnecting
Boolean : set to true if the client is trying to reconnect to the server. false otherwise.
mqtt.Store(options)
In-memory implementation of the message store.
options is the store options:
clean: true, clean inflight messages when close is called (default true)
Other implementations of mqtt.Store:
which uses
to store the inflight
data, making it usable both in Node and the Browser.
to store the inflight
which uses
to store the inflight
data, making it usable in the Browser without browserify.
mqtt.Store#put(packet, callback)
Adds a packet to the store, a packet is
anything that has a messageId property.
The callback is called when the packet has been stored.
mqtt.Store#createStream()
Creates a stream with all the packets in the store.
mqtt.Store#del(packet, cb)
Removes a packet from the store, a packet is
anything that has a messageId property.
The callback is called when the packet has been removed.
mqtt.Store#close(cb)
Closes the Store.
The MQTT.js bundle is available through , specifically
for the full documentation on version ranges.
Weixin App
Surport . See .
Example(js)
var mqtt = require('mqtt')var client
= mqtt.connect('wxs://test.mosquitto.org')
Example(ts)
import { connect } from 'mqtt';const client
= connect('wxs://test.mosquitto.org');
Browserify
In order to use MQTT.js as a browserify module you can either require it in your browserify bundles or build it as a stand alone module. The exported module is AMD/CommonJs compatible and it will add an object in the global space.
npm install -g browserify
install browserifycd node_modules/mqttnpm install .
install dev dependenciesbrowserify mqtt.js -s mqtt & browserMqtt.js
require mqtt in your client-side app
Just like browserify, export MQTT.js as library. The exported module would be var mqtt = xxx and it will add an object in the global space. You could also export module in other
by setting output.libraryTarget in webpack configuration.
npm install -g webpack
install webpack cd node_modules/mqttnpm install .
install dev dependencieswebpack mqtt.js ./browserMqtt.js --output-library mqtt
you can then use mqtt.js in the browser with the same api than node's one.
test Ws mqtt.js src=&./browserMqtt.js&&/
var client = mqtt.connect()
you add a ws:// url here
client.subscribe(&mqtt/demo&)
client.on(&message&, function (topic, payload) {
alert([topic, payload].join(&: &))
client.end()
client.publish(&mqtt/demo&, &hello world!&)
Your broker should accept websocket connection (see
to setup ).
Signed WebSocket Urls
If you need to sign an url, for example for ,
then you can pass in a transformWsUrl function to the
This is needed because signed urls have an expiry and eventually upon reconnects, a new signed url needs to be created:
This module doesn't actually exist, just an examplevar awsIotUrlSigner = require('awsIotUrlSigner')mqtt.connect('wss://a2ukbzaqo9vbpb.iot.ap-southeast-1.amazonaws.com/mqtt', {
transformWsUrl: function (url, options, client) {
It's possible to inspect some state on options(pre parsed url components)
and the client (reconnect state etc)
return awsIotUrlSigner(url)
Now every time a new WebSocket connection is opened (hopefully not that often) we get a freshly signed url
Here is how QoS works:
QoS 0 : received at most once : The packet is sent, and that's it. There is no validation about whether it has been received.
QoS 1 : received at least once : The packet is sent and stored as long as the client has not received a confirmation from the server. MQTT ensures that it will be received, but there can be duplicates.
QoS 2 : received exactly once : Same as QoS 1 but there is no duplicates.
About data consumption, obviously, QoS 2 & QoS 1 & QoS 0, if that's a concern to you.
Usage with TypeScript
This repo bundles TypeScript definition files for use in TypeScript projects and to support tools that can read .d.ts files.
Pre-requisites
Before you can begin using these TypeScript definitions with your project, you need to make sure your project meets a few of these requirements:
TypeScript &= 2.1
Set tsconfig.json: {&compilerOptions& : {&moduleResolution& : &node&}, ...}
Includes the TypeScript definitions for node. You can use npm to install this by typing the following into a terminal window:
npm install --save-dev @types/node
Contributing
MQTT.js is an OPEN Open Source Project. This means that:
Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.
file for more details.
Contributors
MQTT.js is only possible due to the excellent work of the following contributors:
Matteo Collina
Maxime Agor

我要回帖

更多关于 必须使用相同appleid 的文章

 

随机推荐