从零开始写一个聊天应用(客户端)

环境搭建

尝试go的客户端

go get -v github.com/eclipse/paho.mqtt.golang
cd $GOPATH/src/github.com/eclipse/paho.mqtt.golang/cmd/sample
go run main.go -action sub -topic test/topic -broker 192.168.77.170:1883

另一个窗口

mosquitto_pub -t 'test/topic' -m 'hello world'

可以在运行go程序的窗口看到如下


image.png

尝试flutter客户端

flutter create mqtt_client_example
cd mqtt_client_example

添加依赖(pubspec.yaml)

dependencies:
  添加
  mqtt_client: ^5.5.2

拷贝测试代码

 git clone https://github.com/shamblett/mqtt_client.git
cp mqtt_client/example/flutter/lib/* path/to/mqtt_client_example/lib/

修改测试代码
main.dart中


image.png

运行程序
点击connect


image.png

订阅主题


image.png

另一个窗口

mosquitto_pub -t 'test/topic' -m 'hello world'

查看消息


image.png

尝试node和浏览器

初始化

npm init
npm install mqtt

创建index.js,内容如下

var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://192.168.77.170:1883')

client.on('connect', function () {
  client.subscribe('test/topic', function (err) {
  })
})

client.on('message', function (topic, message) {
  console.log(message.toString())
  client.end()
})

测试

node index.js

另一个窗口

mosquitto_pub -t 'test/topic' -m 'hello world'

可以在运行index.js窗口看到信息

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容