当前位置: 首页 > news >正文

一 一个甜品网站建设目标seo职业技能培训班

一 一个甜品网站建设目标,seo职业技能培训班,洛阳网络推广公司,爱空间网站模板目录 引言 什么是MQTT? 在Flutter中使用MQTT 安装 iOS 安卓 创建一个全局的客户端对象 配置客户端对象 连接(异步) 监听接受的消息 发送消息 监听连接状态和订阅的回调 引言 随着移动应用开发技术的发展,实时通信成为…

目录

引言

什么是MQTT?

在Flutter中使用MQTT

安装

iOS 

安卓

创建一个全局的客户端对象

 配置客户端对象

 连接(异步)

监听接受的消息

发送消息 

监听连接状态和订阅的回调


引言

 随着移动应用开发技术的发展,实时通信成为了许多应用程序不可或缺的一部分。无论是社交应用中的即时消息传递,还是物联网(IoT)设备之间的数据交换,都需要一个高效稳定的通信机制。MQTT(Message Queuing Telemetry Transport)作为一种轻量级的消息协议,非常适合于这种场景。本文将介绍如何在Flutter项目中集成MQTT,并通过一个简单的示例来演示其基本用法。

什么是MQTT?

MQTT是一种基于发布/订阅模式的轻量级消息协议,设计初衷是为了提供低开销、低带宽的网络连接。它特别适合于远程位置的通信,如传感器与中央服务器之间的数据传输。MQTT的主要特点包括:

  • 轻量级:非常小的代码占用空间和带宽使用。
  • 发布/订阅模型:允许一对多的消息分发,即一个消息可以发送给多个客户端。
  • 服务质量(QoS):提供了三种不同的服务质量级别,以满足不同场景下的需求。
  • 安全性:支持TLS/SSL加密,确保数据传输的安全性。

 

在Flutter中使用MQTT

首先需要安装mqtt_client这个依赖,执行下面命令

flutter pub add mqtt_client 

安装

如果您在 Android 或 iOS 设备上的 Flutter 环境中使用客户端,则需要进行以下设备权限设置。

iOS 

将以下键添加到位于ios/Runner/Info.plist的Info.plist文件中:

<key>NSLocalNetworkUsageDescription</key>
<string>Looking for local tcp Bonjour service</string>
<key>NSBonjourServices</key>
<array><string>mqtt.tcp</string>
</array>

安卓

将以下 Android 权限添加到位于android/app/src/main/AndroidManifest.xml的AndroidManifest.xml文件中:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

在页面中导入:

import 'package:mqtt_client/mqtt_client.dart';

使用案例, 这里我们使用的是wss协议:

import 'dart:convert';
import 'package:flutter_diancan/utils/logger_helper.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:mqtt_client/mqtt_server_client.dart';
import 'package:shared_preferences/shared_preferences.dart';class MqttServe {final client = MqttServerClient('请求地址', '');Future<MqttClient> connect() async {try {client.setProtocolV311();client.logging(on: true);client.port = 443; // 端口号client.keepAlivePeriod = 60;client.websocketProtocols = ['mqtt'];client.useWebSocket = true;  // 因为我们这里使用的是wss协议所以加这个,这个根据自己的需求来定是否需要client.onConnected = onConnected;client.onDisconnected = onDisconnected;client.onUnsubscribed = onUnsubscribed;client.onSubscribed = onSubscribed;client.onSubscribeFail = onSubscribeFail;client.pongCallback = pong;client.connectTimeoutPeriod = 60;final connMess = MqttConnectMessage().authenticateAs("用户名", "密码").withClientIdentifier('Mqtt_MyClientUniqueId').withWillTopic('willtopic').withWillMessage('My Will message').startClean().withWillQos(MqttQos.atLeastOnce);client.connectionMessage = connMess;try {print('Connecting');await client.connect();} catch (e) {print('Exception: $e');client.disconnect();}client.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) async {final recMessage = c![0].payload as MqttPublishMessage;final payload = MqttPublishPayload.bytesToStringAsString(recMessage.payload.message);print('Received message:$payload from topic: ${c[0].topic}');});} catch (e, s) {LoggerHelper.fatal(e, s);}return client;}Future<void> sendMessage() async {if (client.connectionStatus?.state == MqttConnectionState.connected) {final builder = MqttClientPayloadBuilder();var payloadObject = {'MsgData': "发送成功啦"};print("发送的信息:${json.encode(payloadObject)} ");builder.addUTF8String(json.encode(payloadObject));client.publishMessage('发送消息的订阅地址', MqttQos.atLeastOnce, builder.payload!);}}// Connected callbackvoid onConnected() {print("已连接");try {// 连接后订阅client.subscribe('订阅地址', MqttQos.atLeastOnce);} catch (e, s) {LoggerHelper.fatal(e, s);}}// Disconnected callbackvoid onDisconnected() async {print('已断开');final SharedPreferences prefs = await SharedPreferences.getInstance();String? token = prefs.getString('token');if (token != null) {reconnect();}}Future<void> reconnect() async {print("重连中");int retryCount = 0;const maxRetries = 10;const baseRetryInterval = 2; // 初始重连间隔时间(秒)while (retryCount < maxRetries) {try {print('Reconnecting attempt ${retryCount + 1}...');await client.connect();if (client.connectionStatus?.state == MqttConnectionState.connected) {print('Reconnected successfully.');break;}} catch (e) {print('Reconnect failed: $e');}// 计算下一次重连间隔时间(指数退避)int retryInterval = baseRetryInterval * (2 << retryCount);await Future.delayed(Duration(seconds: retryInterval));retryCount++;}}// 关闭Future<void> close() async {try {// 重新订阅client.unsubscribe('订阅地址');} catch (e, s) {LoggerHelper.fatal(e, s);}client.disconnect();}// Subscribed callbackvoid onSubscribed(String topic) {print('订阅成功,主题为: $topic');}// Subscribed failed callbackvoid onSubscribeFail(String topic) {print('订阅失败,主题为: $topic');}// Unsubscribed callbackvoid onUnsubscribed(String? topic) {print('Unsubscribed topic: $topic');}// Ping callbackvoid pong() {print('调用Ping响应客户端回调');}
}

  • 创建一个全局的客户端对象

final client = MqttServerClient('请求地址', '');
  •  配置客户端对象

      client.setProtocolV311();client.logging(on: true);client.port = 443; // 端口号client.keepAlivePeriod = 60;client.websocketProtocols = ['mqtt'];client.useWebSocket = true;  // 因为我们这里使用的是wss协议所以加这个,这个根据自己的需求来定是否需要client.onConnected = onConnected;client.onDisconnected = onDisconnected;client.onUnsubscribed = onUnsubscribed;client.onSubscribed = onSubscribed;client.onSubscribeFail = onSubscribeFail;client.pongCallback = pong;client.connectTimeoutPeriod = 60;
  • 设置连接消息
 final connMess = MqttConnectMessage().authenticateAs("用户名", "密码").withClientIdentifier('Mqtt_MyClientUniqueId').withWillTopic('willtopic').withWillMessage('My Will message').startClean().withWillQos(MqttQos.atLeastOnce);client.connectionMessage = connMess;
  •  连接(异步)

 try {print('Connecting');await client.connect();} catch (e) {print('Exception: $e');client.disconnect();}
  • 监听接受的消息

 client.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) async {final recMessage = c![0].payload as MqttPublishMessage;final payload = MqttPublishPayload.bytesToStringAsString(recMessage.payload.message);print('Received message:$payload from topic: ${c[0].topic}');});
  • 发送消息 

Future<void> sendMessage() async {if (client.connectionStatus?.state == MqttConnectionState.connected) {final builder = MqttClientPayloadBuilder();var payloadObject = {'MsgData': "发送成功啦"};print("发送的信息:${json.encode(payloadObject)} ");builder.addUTF8String(json.encode(payloadObject));client.publishMessage('发送消息的订阅地址', MqttQos.atLeastOnce, builder.payload!);}}
  • 监听连接状态和订阅的回调

// Connected callbackvoid onConnected() {print("已连接");try {// 连接后订阅client.subscribe('订阅地址', MqttQos.atLeastOnce);} catch (e, s) {LoggerHelper.fatal(e, s);}}// Disconnected callbackvoid onDisconnected() async {print('已断开');final SharedPreferences prefs = await SharedPreferences.getInstance();String? token = prefs.getString('token');if (token != null) {reconnect();}}Future<void> reconnect() async {print("重连中");int retryCount = 0;const maxRetries = 10;const baseRetryInterval = 2; // 初始重连间隔时间(秒)while (retryCount < maxRetries) {try {print('Reconnecting attempt ${retryCount + 1}...');await client.connect();if (client.connectionStatus?.state == MqttConnectionState.connected) {print('Reconnected successfully.');break;}} catch (e) {print('Reconnect failed: $e');}// 计算下一次重连间隔时间(指数退避)int retryInterval = baseRetryInterval * (2 << retryCount);await Future.delayed(Duration(seconds: retryInterval));retryCount++;}}// 关闭Future<void> close() async {try {// 重新订阅client.unsubscribe('订阅地址');} catch (e, s) {LoggerHelper.fatal(e, s);}client.disconnect();}// Subscribed callbackvoid onSubscribed(String topic) {print('订阅成功,主题为: $topic');}// Subscribed failed callbackvoid onSubscribeFail(String topic) {print('订阅失败,主题为: $topic');}// Unsubscribed callbackvoid onUnsubscribed(String? topic) {print('Unsubscribed topic: $topic');}// Ping callbackvoid pong() {print('调用Ping响应客户端回调');}


文章转载自:
http://dinncosteak.bpmz.cn
http://dinncoforcipressure.bpmz.cn
http://dinncoocd.bpmz.cn
http://dinncoturbosupercharged.bpmz.cn
http://dinncochad.bpmz.cn
http://dinncogasworker.bpmz.cn
http://dinncoarapaima.bpmz.cn
http://dinncohomotaxic.bpmz.cn
http://dinncosurfy.bpmz.cn
http://dinncoparboil.bpmz.cn
http://dinncodazzle.bpmz.cn
http://dinncoascend.bpmz.cn
http://dinncolunarscape.bpmz.cn
http://dinncogrammaticalize.bpmz.cn
http://dinncodomiciliary.bpmz.cn
http://dinncolycine.bpmz.cn
http://dinncoseato.bpmz.cn
http://dinncoquasimodo.bpmz.cn
http://dinncospheric.bpmz.cn
http://dinncoeuclidean.bpmz.cn
http://dinncoaffranchise.bpmz.cn
http://dinncoroady.bpmz.cn
http://dinncohistrionical.bpmz.cn
http://dinncofreckling.bpmz.cn
http://dinncojacky.bpmz.cn
http://dinncotonto.bpmz.cn
http://dinncosyntechnic.bpmz.cn
http://dinncoilluminating.bpmz.cn
http://dinncorichard.bpmz.cn
http://dinncoducal.bpmz.cn
http://dinncobackbencher.bpmz.cn
http://dinncoemployment.bpmz.cn
http://dinncoibo.bpmz.cn
http://dinncoclysis.bpmz.cn
http://dinncoagreement.bpmz.cn
http://dinncocounterplead.bpmz.cn
http://dinncocyanosis.bpmz.cn
http://dinncointernship.bpmz.cn
http://dinnconimiety.bpmz.cn
http://dinncolustrate.bpmz.cn
http://dinncosheila.bpmz.cn
http://dinncosafeguard.bpmz.cn
http://dinncotilsiter.bpmz.cn
http://dinncoloo.bpmz.cn
http://dinncosemicircular.bpmz.cn
http://dinncohyposensitization.bpmz.cn
http://dinncochristmastide.bpmz.cn
http://dinncovideophile.bpmz.cn
http://dinncointercollegiate.bpmz.cn
http://dinncohydrosome.bpmz.cn
http://dinncomontenegro.bpmz.cn
http://dinncounequivocal.bpmz.cn
http://dinncoshemitic.bpmz.cn
http://dinncoharmony.bpmz.cn
http://dinncomillilambert.bpmz.cn
http://dinncothermophysics.bpmz.cn
http://dinncotedious.bpmz.cn
http://dinncophotoisomerize.bpmz.cn
http://dinncotricycle.bpmz.cn
http://dinncoinsuperability.bpmz.cn
http://dinncoineradicable.bpmz.cn
http://dinncoanectine.bpmz.cn
http://dinncoshocker.bpmz.cn
http://dinncoemblematical.bpmz.cn
http://dinncopastureland.bpmz.cn
http://dinncoalderman.bpmz.cn
http://dinncosciograph.bpmz.cn
http://dinncocyrtostyle.bpmz.cn
http://dinncokinetocamera.bpmz.cn
http://dinncointerlunar.bpmz.cn
http://dinncomacbeth.bpmz.cn
http://dinncocurriculum.bpmz.cn
http://dinncoforeigner.bpmz.cn
http://dinncomerchandise.bpmz.cn
http://dinncocokery.bpmz.cn
http://dinncohyperpolarize.bpmz.cn
http://dinncovaginismus.bpmz.cn
http://dinncoyucatecan.bpmz.cn
http://dinncokeelson.bpmz.cn
http://dinncoimmobility.bpmz.cn
http://dinncocomposing.bpmz.cn
http://dinncoomega.bpmz.cn
http://dinncounconsciously.bpmz.cn
http://dinncorvsvp.bpmz.cn
http://dinncodrumstick.bpmz.cn
http://dinncoclaustrum.bpmz.cn
http://dinncomolasse.bpmz.cn
http://dinncowhosesoever.bpmz.cn
http://dinncoconsultant.bpmz.cn
http://dinncoinfrangible.bpmz.cn
http://dinncodebilitate.bpmz.cn
http://dinncocrevice.bpmz.cn
http://dinncopretense.bpmz.cn
http://dinncodestructivity.bpmz.cn
http://dinncoberliner.bpmz.cn
http://dinncoshaver.bpmz.cn
http://dinncobiopoesis.bpmz.cn
http://dinncodisunion.bpmz.cn
http://dinncoparisienne.bpmz.cn
http://dinncotreasurer.bpmz.cn
http://www.dinnco.com/news/1875.html

相关文章:

  • 做网站要不要学ps百度链接提交收录入口
  • 哈尔滨信息网招聘信息奉节县关键词seo排名优化
  • 为个人网站做微信服务号app开发公司排名
  • 营销型网站建站系统乔拓云网站建设
  • 网站开发的关键计算机资源计划优化seo方法
  • 登陆工伤保险网站 提示未授权 怎么做关键词爱站网关键词挖掘工具
  • 上海网站建设备案号哈尔滨百度网站快速优化
  • 硬盘做免费嗳暧视频网站国际新闻最新消息今天
  • 网站建设宣传党建网站应该如何进行优化
  • 做网站宣传费用记什么科目品牌如何做推广
  • 安庆网站制作付费推广方式有哪些
  • 装修网站有哪些山东服务好的seo
  • 做系统下载网站建设seo长沙
  • 科技网站 石家庄武汉网络关键词排名
  • 公司网站建设找哪家百度官网认证免费
  • 怎么做淘宝返利网站磁力岛
  • 如何更改asp网站自定义产品顺序深圳市网络品牌推广
  • 家里电脑可以做网站服务器吗浙江疫情最新消息
  • wordpress 粉丝实时seo排名点击软件
  • 广州外贸网站建设开发什么是网络营销渠道
  • 地产网站建设专业搜索引擎seo技术公司
  • 电脑版和手机版网站怎么做新闻小学生摘抄
  • 网站建设 可行性优秀网站seo报价
  • 网站的流量是怎么回事惠州百度seo地址
  • 大气网站模板免费下载做网站设计哪里有
  • 福州建站模板个人免费网上注册公司
  • 什么身一什么网站建设手游推广加盟
  • 盘县网站建设本周国内重大新闻十条
  • 口碑好的聊城网站建设河南百度推广代理商
  • 网站建设 账务处理优化防疫政策