# mqtt-Wechat **Repository Path**: adbshell/mqtt-wechat ## Basic Information - **Project Name**: mqtt-Wechat - **Description**: 一个在微信小程序中测试成功可用的mqtt.js版本 - **Primary Language**: JavaScript - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 4 - **Created**: 2021-06-11 - **Last Updated**: 2021-06-11 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # mqtt-Wechat🛰 原作者项目地址:[MQTT.js](https://github.com/mqttjs/MQTT.js#weapp) #### 介绍 一个在微信小程序中测试成功可用的mqtt.js版本。 因用npm install或者直接下载github上面的 [MQTT.js](https://github.com/mqttjs/MQTT.js#weapp) 在微信小程序中使用碰到了各种问题,干脆就备份一个可用的版本到 [mqtt-wechat](https://gitee.com/w2cxy/mqtt-wechat) 注意微信小程序只能用wss协议,ws协议可以用来测试,但是要在微信开发工具中关闭安全通信校验。 ![关闭SSL校验](setting.png) #### 安装教程 直接下载[mqtt.js](https://gitee.com/w2cxy/mqtt-wechat/blob/master/mqtt.js) 保存到项目代码文件中。 #### 使用说明 🍐connect: - 需指定protocol为"wxs"或者"wx"否则库会当成在浏览器中,从而无法工作 ``` import mqtt from "./mqtt"; const client = mqtt.connect('wss://test.mosquitto.org', {protocol: "wxs"}); ``` - 或者修改URL,如你的链接是wss://则修改为wxs://,如果你的链接是ws://则修改为wx:// ``` import mqtt from "./mqtt"; const client = mqtt.connect('wxs://test.mosquitto.org'); ``` 🌰例子: ```javascript import mqtt from "./mqtt"; var client = mqtt.connect('wss://test.mosquitto.org', { protocol: "wxs", clientId: 'wechat_' + Math.random().toString(16).substr(2, 8), username: 'your username', password: 'your password', keepalive: 60, }); client.on('connect', function () { client.subscribe('presence', function (err) { if (!err) { client.publish('presence', 'Hello mqtt') } }) }) client.on('message', function (topic, message) { // message is Buffer console.log(message.toString()) client.end() }) ```