mqtt flutter web项目websocket
在网上找相关的代码学习,太少了,自己借鉴研究了一个
pubspec.yaml添加引用包
dependencies:
flutter:
sdk: flutter
fast_gbk: 1.0.0
mqtt_client: ^10.2.0
mqtt代码:
import 'package:mqtt_client/mqtt_browser_client.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:typed_data/typed_data.dart';
import 'package:fast_gbk/fast_gbk.dart';///有好的修改方式请联系我修改文章帮助更多人 谢谢
///https://blog.csdn.net/ZQ200720/article/details/139065097?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22139065097%22%2C%22source%22%3A%22ZQ200720%22%7D
class webMqtt {late final MqttBrowserClient client;bool isbool = false;conn(String clientid) async {client =MqttBrowserClient.withPort('ws://127.0.0.1:8083/mqtt', clientid, 8083);//client.logging(on: true); //打印详细client.onConnected = () {isbool = true;print('Connected 已连接');};client.onDisconnected = () {isbool = false;print('Disconnected 未连接');};client.onUnsubscribed = (topic) {print("未订阅:$topic");// print('Unsubscribed from $topic');};client.onSubscribed = (topic) {print("已订阅:$topic");// print('Subscribed to $topic');///在订阅成功的时候注册消息监听client.updates?.listen(_onData);};client.onAutoReconnect=(){print("onAutoReconnect");//自动重新连接时};client.onAutoReconnected=(){print("onAutoReconnected");//自动恢复时};client.onSubscribeFail=(topic){print("onSubscribeFail: $topic");//订阅失败时};try {//配置连接信息final connMessage = MqttConnectMessage().authenticateAs('your_username', 'your_password').keepAliveFor(60)//失效.withWillTopic('will_topic').withWillMessage('LWT message').startClean();client.connectionMessage = connMessage;await client.connect(); //连接if (client.connectionStatus == true) {print('Connected to MQTT broker.');// 监听发送更新事件// client.updates?.forEach((element) {// final MqttPublishMessage recMess = element.payload as MqttPublishMessage;// //final String pt = MqttPublishPayload.bytesToStringAsString(recMess.payload.message);// // print("2收到$subTopic消息:$pt"); //字符串// print(recMess.payload.message.toString()); //字符串// });/*client.published?.forEach((element) {final MqttPublishMessage recMess = element.payload as MqttPublishMessage;print(recMess.payload.message.toString()); //字符串});*//* //无法回调client.published?.listen((MqttPublishMessage message) {// Handle the incoming message.// Check if the payload is a string or binary and handle accordingly.if (message.payload is String) {print('Received string message: ${message.payload}');} else if (message.payload is List<int>) {// If the payload is binary data, you might want to convert it to a string or handle it as bytes.String messageAsString =String.fromCharCodes(message.payload as List<int>);print('Received binary message: $messageAsString');}}, onError: (error) {// Handle any errors in the stream.print('Error receiving messages: $error');}, onDone: () {// Handle the completion of the stream.print('No more messages.');});*/} else {print('Failed to connect to MQTT broker.');}} catch (e) {print('连接失败:$e');}}///消息监听_onData(List<MqttReceivedMessage<MqttMessage>> data) {/* Uint8Buffer uint8buffer = Uint8Buffer();var messageStream = MqttByteBuffer(uint8buffer);data.forEach((MqttReceivedMessage<MqttMessage> m) {///将数据写入到messageStream数组中m.payload.writeTo(messageStream);print(uint8buffer.toString()); //字节final String pt =MqttPublishPayload.bytesToString(uint8buffer);print("1收到$subTopic消息:$pt");});
*/data.forEach((MqttReceivedMessage<MqttMessage> m) {final MqttPublishMessage recMess = m.payload as MqttPublishMessage;//final String pt = MqttPublishPayload.bytesToStringAsString(recMess.payload.message);// print("2收到$subTopic消息:$pt"); //字符串print(recMess.payload.message.toString()); //字符串//乱码处理// final bytes = gbk.encode(recMess.payload.message.toString()); //获取字节流 string -- bytesfinal status = gbk.decode(recMess.payload.message);print("接收消息:$status"); //字符串// final info = UserInfo("消息:$status", 18);// sdata().getEve(info);});}//订阅主题void subscribe(String top) {if (isbool) client.subscribe(top, MqttQos.atLeastOnce);}//取消订阅主题void unsubscribe(String top) {if (isbool) client.unsubscribe(top); //.subscribe(top, MqttQos.atLeastOnce);}//发送消息void publishMessage(String top, String mesg) {if (!isbool) {print('没有连接');return;}///int数组Uint8Buffer uint8buffer = Uint8Buffer();///字符串转成int数组 (dart中没有byte) 类似于java的String.getBytes?var codeUnits = mesg.codeUnits;uint8buffer.addAll(codeUnits);client.publishMessage(top, MqttQos.atLeastOnce, uint8buffer);}//断开连接void disconn() {if (isbool) client.disconnect();}
}
使用
import 'package:flutter/material.dart';import 'package:webwsyn/mqtt/web_mqtt.dart';Future<void> main() async {runApp(MyApp());
}class MyApp extends StatelessWidget {Widget build(BuildContext context) {return MaterialApp(title: 'Flutter Demo',home: MqttDemo(), //Column(),);}
}class MqttDemo extends StatefulWidget { _MqttDemoState createState() => _MqttDemoState();
}class _MqttDemoState extends State<MqttDemo> {webMqtt _mqttService = webMqtt();String clientid = "textmqtt";void initState() {super.initState();//connectToMqtt1();}void dispose() {super.dispose();}void _conn() {_mqttService = webMqtt();_mqttService.conn(clientid);}void _disconn() {_mqttService.disconn();}void _subscribe() {_mqttService.subscribe('test/topic');}void _unsubscribe(){_mqttService.unsubscribe('test/topic');}void _sendMessage() {_mqttService.publishMessage('test/topic', 'Hello MQTT from Flutter Web!');}Widget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text('MQTT Demo'),),body: Column(children: [Center(child: ElevatedButton(onPressed: _conn,child: Text('连接'),),),Center(child: ElevatedButton(onPressed: _subscribe,child: Text('订阅'),),),Center(child: ElevatedButton(onPressed: _unsubscribe,child: Text('取消订阅'),),),Center(child: ElevatedButton(onPressed: _sendMessage,child: Text('发送'),),),Center(child: ElevatedButton(onPressed: _disconn,child: Text('断开'),),),],),);}
}
创作不易,请留下你的鼓励,谢谢