浏览器 mqtt客户端 基于nodejs

    之前用到的mqtt都是在后台简历MQTT连接,现在想不要后台,直接在前端建立MQTT客户端,更方便实用。

    1).首先需要下载nodejs 然后用nodejs自带的npm模块安装Mosca

     2).在nodejs 路径下添加一个server.js ,内容如下:()

var mosca = require('mosca');

var ascoltatore = {
  //using ascoltatore
 
};

var settings = {
	http: {
		port: 1884,
		bundle: true,
		static: './'
	  },
  backend: ascoltatore
};

var server = new mosca.Server(settings);

server.on('clientConnected', function(client) {
    console.log('client connected', client.id);
});

// fired when a message is received
server.on('published', function(packet, client) {
  console.log('Published', packet.payload);
});

server.on('ready', setup);

// fired when the mqtt server is ready
function setup() {
  console.log('Mosca server is up and running');
}

    3).打开doc窗口,在node 的安装路径下运行server.js。如图:

4).js代码如下: 

                client = new Paho.MQTT.Client('192.168.168.104', 1884, "bbb");

		// set callback handlers
		client.onConnectionLost = onConnectionLost;
		client.onMessageArrived = onMessageArrived;

		// connect the client
		client.connect({
			onSuccess: onConnect
		});

		// called when the client connects
		function onConnect() {
			// Once a connection has been made, make a subscription and send a message.
			console.log("onConnect");
			client.subscribe("主题");
			message = new Paho.MQTT.Message("111111111");
			message.destinationName = "主题";
			client.send(message);
		}

		// called when the client loses its connection
		function onConnectionLost(responseObject) {
			if(responseObject.errorCode !== 0) {
				console.log("onConnectionLost:" + responseObject.errorMessage);
			}
		}

		// called when a message arrives
		function onMessageArrived(message) {
			console.log("onMessageArrived:" + message.payloadString);
		}

亲测有效!!!!

注意:页面需要调用mqttws31.js

https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js

    

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值