fusesource/mqtt-client

mqtt推送实践 最近公司开发项目,用到了推送技术,这里不分析各种推送技术的优劣了,网上内容一大堆,通过查看别人的对比资料以及实践,最后选择了mqtt这个推送协议。     mqtt既然是一个协议,自然就有它的实现了,相关的客户端和服务器端实现可以在这个网址下找到:https://github.com/mqtt/mqtt.github.io/wiki/software?id=software,这里服务器端实现我选 阅读详情

Sign in or Sign up

 fusesource/mqtt-client

 Code  Issues 66  Pull requests 6  Projects 0  Insights

Dismiss

Join GitHub today

GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.

Sign up

A Java MQTT Client http://mqtt-client.fusesource.org/

  1. Java 93.6%
  2. CSS 2.6%
  3. Scala 2.5%
  4. HTML 1.3%

Java CSS Scala HTML

Branch: master

 Switch branches/tags

 

 master

Nothing to show

 mqtt-client-project-1.14  mqtt-client-project-1.13  mqtt-client-project-1.12  mqtt-client-project-1.11  mqtt-client-project-1.10  mqtt-client-project-1.9  mqtt-client-project-1.8  mqtt-client-project-1.7  mqtt-client-project-1.6  mqtt-client-project-1.5  mqtt-client-project-1.4  mqtt-client-project-1.3  mqtt-client-project-1.2  mqtt-client-project-1.1  mqtt-client-project-1.0

Nothing to show

New pull request

Find file

Clone or download 

@chirino

chirino [maven-release-plugin] prepare for next development iteration

Latest commit 1c8a86a May 31, 2016

 Failed to load latest commit information.
 mqtt-client-java1.4-uber[maven-release-plugin] prepare for next development iterationMay 31, 2016
 mqtt-client-website[maven-release-plugin] prepare for next development iterationMay 31, 2016
 mqtt-client[maven-release-plugin] prepare for next development iterationMay 31, 2016
 src/main/resourcesUpdate license headers.May 3, 2012
 .gitignoreAdd the unsubscribe method to the future and blocking apisFeb 5, 2012
 license.txtInitial Spike of the MQTT client lib. Extracted from experiment in st…Dec 17, 2011
 pom.xml[maven-release-plugin] prepare for next development iterationMay 31, 2016
 readme.mdMerge pull request #58 from mdanter/patch-1Mar 24, 2016

 readme.md

Overview

MQTT is a machine-to-machine (M2M)/"Internet of Things" connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. It is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium.

mqtt-client provides an ASL 2.0 licensed API to MQTT. It takes care of automatically reconnecting to your MQTT server and restoring your client session if any network failures occur. Applications can use a blocking API style, a futures based API, or a callback/continuations passing API style.

Using from Maven

Add the following to your maven pom.xml file.

<dependency>
  <groupId>org.fusesource.mqtt-client</groupId>
  <artifactId>mqtt-client</artifactId>
  <version>1.12</version>
</dependency>

Using from Gradle

Add the following to your gradle file.

compile 'org.fusesource.mqtt-client:mqtt-client:1.12'

Using from any Other Build System

Download the uber jar file and add it to your build. The uber contains all the stripped down dependencies which the mqtt-client depends on from other projects.

Using on Java 1.4

We also provide an java 1.4 uber jar file which is compatible with Java 1.4 JVMs. This version of the jar does not support SSL connections since the SSLEngine class used to implement SSL on NIO was not introduced until Java 1.5.

Configuring the MQTT Connection

The blocking, future, and callback APIs all share the same connection setup. You create a new instance of the MQTT class and configure it with connection and socket related options. At a minimum the setHost method be called before attempting to connect.

MQTT mqtt = new MQTT();
mqtt.setHost("localhost", 1883);
// or 
mqtt.setHost("tcp://localhost:1883");

Controlling MQTT Options

  • setClientId : Use to set the client Id of the session. This is what an MQTT server uses to identify a session where setCleanSession(false); is being used. The id must be 23 characters or less. Defaults to auto generated id (based on your socket address, port and timestamp).

  • setCleanSession : Set to false if you want the MQTT server to persist topic subscriptions and ack positions across client sessions. Defaults to true.

  • setKeepAlive : Configures the Keep Alive timer in seconds. Defines the maximum time interval between messages received from a client. It enables the server to detect that the network connection to a client has dropped, without having to wait for the long TCP/IP timeout.

  • setUserName : Sets the user name used to authenticate against the server.

  • setPassword : Sets the password used to authenticate against the server.

  • setWillTopic: If set the server will publish the client's Will message to the specified topics if the client has an unexpected disconnection.

  • setWillMessage: The Will message to send. Defaults to a zero length message.

  • setWillQos : Sets the quality of service to use for the Will message. Defaults to QoS.AT_MOST_ONCE.

  • setWillRetain: Set to true if you want the Will to be published with the retain option.

  • setVersion: Set to "3.1.1" to use MQTT version 3.1.1. Otherwise defaults to the 3.1 protocol version.

Controlling Connection Reconnects

Connection will automatically reconnect and re-establish messaging session if any network error occurs. You can control how often the reconnect is attempted and define maximum number of attempts of reconnects using the following methods:

  • setConnectAttemptsMax : The maximum number of reconnect attempts before an error is reported back to the client on the first attempt by the client to connect to a server. Set to -1 to use unlimited attempts. Defaults to -1.
  • setReconnectAttemptsMax : The maximum number of reconnect attempts before an error is reported back to the client after a server connection had previously been established. Set to -1 to use unlimited attempts. Defaults to -1.
  • setReconnectDelay : How long to wait in ms before the first reconnect attempt. Defaults to 10.
  • setReconnectDelayMax : The maximum amount of time in ms to wait between reconnect attempts. Defaults to 30,000.
  • setReconnectBackOffMultiplier : The Exponential backoff be used between reconnect attempts. Set to 1 to disable exponential backoff. Defaults to 2.

Configuring Socket Options

You can adjust some socket options by using the following methods:

  • setReceiveBufferSize : Sets the size of the internal socket receive buffer. Defaults to 65536 (64k)

  • setSendBufferSize : Sets the size of the internal socket send buffer.
    Defaults to 65536 (64k)

  • setTrafficClass : Sets traffic class or type-of-service octet in the IP header for packets sent from the transport. Defaults to 8 which means the traffic should be optimized for throughput.

Throttling Connections

If you want slow down the read or write rate of your connections, use the following methods:

  • setMaxReadRate : Sets the maximum bytes per second that this transport will receive data at. This setting throttles reads so that the rate is not exceeded. Defaults to 0 which disables throttling.

  • setMaxWriteRate : Sets the maximum bytes per second that this transport will send data at. This setting throttles writes so that the rate is not exceeded. Defaults to 0 which disables throttling.

Using SSL connections

If you want to connect over SSL/TLS instead of TCP, use an "ssl://" or "tls://" URI prefix instead of "tcp://" for the host field. For finer grained control of which algorithm is used. Supported protocol values are:

  • ssl:// - Use the JVM default version of the SSL algorithm.
  • sslv*:// - Use a specific SSL version where * is a version supported by your JVM. Example: sslv3
  • tls:// - Use the JVM default version of the TLS algorithm.
  • tlsv*:// - Use a specific TLS version where * is a version supported by your JVM. Example: tlsv1.1

The client will use the default JVM SSLContext which is configured via JVM system properties unless you configure the MQTT instance using thesetSslContext method.

SSL connections perform blocking operations against internal thread pool unless you call the setBlockingExecutor method to configure that executor they will use instead.

Selecting the Dispatch Queue

A HawtDispatch dispatch queue is used to synchronize access to the connection. If an explicit queue is not configured via the setDispatchQueuemethod, then a new queue will be created for the connection. Setting an explicit queue might be handy if you want multiple connection to share the same queue for synchronization.

Using the Blocking API

The MQTT.connectBlocking method establishes a connection and provides you a connection with an blocking API.

BlockingConnection connection = mqtt.blockingConnection();
connection.connect();

Publish messages to a topic using the publish method:

connection.publish("foo", "Hello".getBytes(), QoS.AT_LEAST_ONCE, false);

You can subscribe to multiple topics using the the subscribe method:

Topic[] topics = {new Topic("foo", QoS.AT_LEAST_ONCE)};
byte[] qoses = connection.subscribe(topics);

Then receive and acknowledge consumption of messages using the receive, and ack methods:

Message message = connection.receive();
System.out.println(message.getTopic());
byte[] payload = message.getPayload();
// process the message then:
message.ack();

Finally to disconnect:

connection.disconnect();

Using the Future based API

The MQTT.connectFuture method establishes a connection and provides you a connection with an futures style API. All operations against the connection are non-blocking and return the result via a Future.

FutureConnection connection = mqtt.futureConnection();
Future<Void> f1 = connection.connect();
f1.await();

Future<byte[]> f2 = connection.subscribe(new Topic[]{new Topic(utf8("foo"), QoS.AT_LEAST_ONCE)});
byte[] qoses = f2.await();

// We can start future receive..
Future<Message> receive = connection.receive();

// send the message..
Future<Void> f3 = connection.publish("foo", "Hello".getBytes(), QoS.AT_LEAST_ONCE, false);

// Then the receive will get the message.
Message message = receive.await();
message.ack();

Future<Void> f4 = connection.disconnect();
f4.await();

Using the Callback/Continuation Passing based API

The MQTT.connectCallback method establishes a connection and provides you a connection with an callback style API. This is the most complex to use API style, but can provide the best performance. The future and blocking APIs use the callback api under the covers. All operations on the connection are non-blocking and results of an operation are passed to callback interfaces you implement.

Example:

final CallbackConnection connection = mqtt.callbackConnection();
connection.listener(new Listener() {
  
    public void onDisconnected() {
    }
    public void onConnected() {
    }

    public void onPublish(UTF8Buffer topic, Buffer payload, Runnable ack) {
        // You can now process a received message from a topic.
        // Once process execute the ack runnable.
        ack.run();
    }
    public void onFailure(Throwable value) {
        connection.close(null); // a connection failure occured.
    }
})
connection.connect(new Callback<Void>() {
    public void onFailure(Throwable value) {
        result.failure(value); // If we could not connect to the server.
    }

    // Once we connect..
    public void onSuccess(Void v) {
    
        // Subscribe to a topic
        Topic[] topics = {new Topic("foo", QoS.AT_LEAST_ONCE)};
        connection.subscribe(topics, new Callback<byte[]>() {
            public void onSuccess(byte[] qoses) {
                // The result of the subcribe request.
            }
            public void onFailure(Throwable value) {
                connection.close(null); // subscribe failed.
            }
        });

        // Send a message to a topic
        connection.publish("foo", "Hello".getBytes(), QoS.AT_LEAST_ONCE, false, new Callback<Void>() {
            public void onSuccess(Void v) {
              // the pubish operation completed successfully.
            }
            public void onFailure(Throwable value) {
                connection.close(null); // publish failed.
            }
        });
        
        // To disconnect..
        connection.disconnect(new Callback<Void>() {
            public void onSuccess(Void v) {
              // called once the connection is disconnected.
            }
            public void onFailure(Throwable value) {
              // Disconnects never fail.
            }
        });
    }
});

Every connection has a HawtDispatch dispatch queue which it uses to process IO events for the socket. The dispatch queue is an Executor that provides serial execution of IO and processing events and is used to ensure synchronized access of connection.

The callbacks will be executing the dispatch queue associated with the connection so it safe to use the connection from the callback but you MUST NOT perform any blocking operations within the callback. If you need to perform some processing which MAY block, you must send it to another thread pool for processing. Furthermore, if another thread needs to interact with the connection it can only do it by using a Runnable submitted to the connection's dispatch queue.

Example of executing a Runnable on the connection's dispatch queue:

connection.getDispatchQueue().execute(new Runnable(){
    public void run() {
      connection.publish( ..... );
    }
});

 

使用fusesource的mqtt-client-1.7-uber.jar,mqtt发布消息出去,接收端看到的是中文乱码,如何解决? ok,以上就是我这期的Bug修复内容啦,如果还想查找更多解决方案,你可以看看我专门收集Bug及提供解决方案的专栏「Bug调优」,都是实战中碰到的Bug,希望对你有所帮助。到此,咱们下期拜拜。码字不易,如果这篇文章对你有所帮助,帮忙给bugj菌来个,您的支持就是我坚持写作分享知识点传播技术的最大动力。「猿圈奇妙屋」; 阅读详情

相关推荐

mqtt-client:一个Java MQTT客户端

概述 MQTT是机器对机器(M2M)/“物联网”连接协议。 它被设计为一种非常轻量级的发布/订阅消息传递。 对于与需要较小代码占用和/或网络带宽非常宝贵的远程位置的连接很有用。 mqtt-client为MQTT提供了ASL 2.0许可的API。 如果发生任何网络故障,它将自动重新连接到MQTT服务器并还原您的客户端会话。 应用程序可以使用阻塞API样式,基于期货的API或回调/继续传递API样式。 从Maven使用 将以下内容添加到您的maven pom.xml文件中。 <dependency> <groupId>org.fusesource.mqtt-client</groupId> <artifactId>mqtt-client</artifactId> <version>1.12</version> </dependency> 从Gradle使用 将以下内容添加到您的

java,mqtt-client开发创建客户端

java,Mqtt开发

IDEAT科技的博客 3887

SpringBoot集成EMQTT消息队列客户端演示项目_使用org_fusesource_mqtt_client实现MQTT协议通信的物联网消息推送系统_通过SpringBoot.zip

SpringBoot集成EMQTT消息队列客户端演示项目_使用org_fusesource_mqtt_client实现MQTT协议通信的物联网消息推送系统_通过SpringBoot.zip

MQTT客户端JAVA代码----fusesource mqtt-client

前言: fusesource版本:mqtt-client-1.7-uber.jar 下载地址:https://github.com/fusesource/mqtt-client fusesource提供三种mqtt...

clmaykr95629的博客 674

springboot-emqtt-demo:原始码的主要学习SpringBoot + EMQTT消息服务项目构建,EMQTT客户端使用org.fusesource.mqtt-client,内容包括建立MQTT服务监听,消息订阅,发布,取消订阅,遗愿消息设置,以及使用swagger2组件调试消息发布API

springboot-emqtt-demo客户端使用org.fusesource.mqtt-client,没有org.eclipse.paho.client.mqttv3客户端稳定

solidworks实体显示线框

solidworks实体莫名其妙显示为有点虚的线框

qq_35858902的博客 1万+

MQTT-Client-fusesource源码(pub/sub)

大佬写的,看的懵懵懂懂,记录下来收藏 1、publish发布主题发布消息 package jmh.fusesource; import java.net.URISyntaxException; import org.eclipse.paho.client.mqttv3.MqttException; import org.fusesource.mqtt.client.BlockingConn...

愚者 533

数字图像处理第九章笔记

目录一、腐蚀与膨胀1、腐蚀2、膨胀3、对偶性4、开操作与闭操作二、一些基本的形态学算法1、边界提取2、孔洞填充3、连通分量提取4、凸壳5、细化6、粗化7、骨架8、形态学重建三、灰度级形态学1、腐蚀和膨胀2、开运算和闭运算3、灰度级形态学算法 一、腐蚀与膨胀 1、腐蚀 腐蚀可以去除图像的某些部分。 2、膨胀 膨胀可以连接裂缝。 3、对偶性 膨胀和腐蚀彼此关于集合求补运算和反射运算是对偶的 4、开操作与闭操作 开操作:B对A先腐蚀,再进行膨胀 可以平滑物体轮廓,断开较窄的狭颈并消除较细的突出物。 闭操作

方悔读书迟 1375

MQTT fusesource / mqtt-client 原Git项目翻译

MQTT是一款针对机对机(M2M)通信的,非常轻量级的的消息订阅、发布协议。它适用于一些系统资源和网络带宽非常有限的情况下的远程连接。MQTT-Client提供一个ASL 2.0证书下的MQTT接口。在网络连接失败时,它能够自动地重新连接服务器并尝试恢复会话。应用程序能够使用阻塞API、基于Future的API和回调API,共三种接口形式。   在Maven中引用MQTT-Client

迷茫的岁月的专栏 1063

Livox MID360与Fast-LIO2的实战部署指南:从驱动安装到点云处理

本文提供Livox MID360激光雷达与Fast-LIO2激光惯性里程计从零开始的实战部署指南。详细介绍了Ubuntu系统下的驱动安装、网络配置、点云数据验证以及Fast-LIO2算法的编译、参数配置与联合启动流程,帮助开发者快速搭建移动机器人SLAM系统,并包含关键参数调优与常见故障排查方法。

java5的博客 1026

56、宇宙微波背景辐射(CMB)望远镜及光学系统解析

本文详细解析了宇宙微波背景辐射(CMB)望远镜及其光学系统,重点介绍了交叉德拉贡系统的结构特点、偏振测量误差及其控制、以及大型地面望远镜如ACT和SPT的设计与对比。同时,总结了不同光学系统和探测器阵列的优劣势,并展望了未来发展方向,旨在为CMB研究提供更高效的工具和技术支持。

f9g0h的博客 245

【亲测免费】 MQTT-Client: 一个功能强大的MQTT客户端库

是一个由FuseSource开发的开源库,它提供了一个简单易用的API,用于在Java应用程序中实现MQTT协议的支持。 ## 什么是MQTT? MQTT是一种轻量级的消息传输协议,用于在物联网设备之间交换数据。它是专门为低带宽、高延迟和不稳定的网络连接设计的。MQTT协议支持发布/订阅模型,使得消息可以在多个设备之间可靠地传递。 ## MQTT-Client的功能与应用场景 使用MQTT...

gitblog_00058的博客 1711

Yolov8-pose关键点检测:loss优化 | LRM loss困难样本挖掘,提升难样本、遮挡物等检测精度

LRM loss应用到能够大幅提升pose遮挡物性能

①答疑群聊服务;②YOLO大模型知识问答系统;③计算机视觉论文生成智能体; 1716

mqtt-client回调方法简介

使用Fusesource mqtt-client作为mqtt客户包使用,其总共提供了三种API: 1.Blocking API(阻塞式API) 2.Future based API 3.Callback/Continuation(阻塞式API) 其中第三种Callback阻塞式是前两种的基础,可以通过前两种的源码中证明: public FutureConnection(CallbackC

showmyself 1万+

通信算法之283:大疆DJI云哨系统-DJI DroneID物理层协议-解速率匹配及Turbo译码

3. 完整云哨接收机,接收灵敏度。交流: 1279682290 ,2. Turbo译码模块。1. 解速率匹配模块。

leegang12的专栏 868

【即插即用模块】Transformer篇 | ICCV 2025 | MALA :注意力分布神似Softmax,告别线性注意力性能短板!

MALA(Magnitude-Aware Linear Attention)是一种改进的线性注意力机制,通过引入缩放因子和偏移项,解决了传统线性注意力忽视查询幅度的问题,使其分布更接近Softmax Attention。该模块具有线性复杂度(O(n)),结合RoPE和LEPE编码实现全局-局部位置信息混合,通过z值调制平衡信息权重。实验表明MALA在轻量级视觉任务中能有效平衡效率与精度,注意力可视化显示其分布与Softmax Attention高度相似。代码提供完整的RoPE位置编码和线性注意力

主要更新底层视觉(去噪、超分等)相关的科研内容,形式为【论文精读】+【论文复现】 1108

MQTT fusesource 的 Callback API 消息发布的实现

当QoS level 1的时候 发布消息时,Server会回调通知客户端。fusesource 有实现带callback的发布方式。 所有QoS level 1都要在可变头部中附加一个16位的消息ID。 SUBSCRIBE和UNSUBSCRIBE消息使用QoS level 1。 针对消息的发布,Qos level 1,意味着消息至少被传输一次。 发送者若在一段时间内接收

天天的专栏 7098

图文:银行核心账务处理逻辑(白话篇)

银行账务系统分为对内账(记录银行自身资产负债)和对外账(处理客户交易),通过特定编码规则的账号体系进行管理。采用T型账户结构和凭证制度确保每笔交易可追溯,通过明细核算与综合核算双线并行、每日轧账核对(科目日结单、总账、日计表)实现账务精准平衡。从业务触发到最终账平的全流程体现了银行账务"分层记录、双向核对、闭环校验"的核心原则,保障资金流动的透明性与安全性。

银行信息系统应用架构详解 544

采用MQTT协议实现android消息推送(4)选fusesource-mqtt-client为客户端

1.简介   一个java写的mqtt客户端。项目地址:   https://github.com/fusesource/mqtt-client 2.引入fusesource-mqtt-client库 File--->Project Structure--->Dependencies 点绿色+ 在弹出的窗口中输入“‘mqtt-client”回车搜索 在结果中...

banyinlve3147的博客 456

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

mqttjar包_MQTT客户端代码 -- JAVA fusesource mqtt-client

转:http://ywx217.iteye.com/blog/1797463MQTT是一款针对机对机(M2M)通信的,非常轻量级的的消息订阅、发布协议。它适用于一些系统资源和网络带宽非常有限的情况下的远程连接。MQTT-Client提供一个ASL 2.0证书下的MQTT接口。在网络连接失败时,它能够自动地重新连接服务器并尝试恢复会话。应用程序能够使用阻塞API、基于Future的API和回调API...

weixin_39866087的博客 610

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

MQTT协议之使用Future模式订阅及发布(使用fusesource mqtt-client实现)

fusesource提供三种mqtt client api: 阻塞API,基于Futur的API和回调API。其中,回调API是最复杂的也是性能最好的,另外两种均是对回调API的封装。 我们下面就简单介绍一下回调API的使用方法。

任何技能都是从模仿开始,逐步升华。 1万+

MQTT 客户端JAVA代码 fusesource mqtt-client

前言: fusesource版本:mqtt-client-1.7-uber.jar 下载地址:https://github.com/fusesource/mqtt-client fusesource提供三种mqtt client api: 阻塞API,基于Futur的API和回调API。其中,回调API是最复杂的也是性能最好的,另外两种均是对回调API的封装。 我们下面就简单介绍一下回调AP

迷茫的岁月的专栏 2337

MQTT org.fusesource.mqtt 实例

最新maven 依赖 org.fusesource.mqtt-client mqtt-client 1.10 Server发布主题

天天的专栏 1万+
上一篇: ITPub博客
下一篇: Storm环境配置及吞吐量测试调优总结
王树民
博客等级 码龄10年 912粉丝 560原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值