Web页面通过MQTT协议与服务器交互,Mosca安装测试

在服务器上安装node的执行环境和mosca库

yum install nodejs
yum install zeromq-devel

mkdir devel
cd  devel

npm install --save  mosca

node  mqttserver.js

mqttserver.js源码如下:

需要说明一下的就是,源码中的6000端口代表的就是mqtt server的监听端口,  mqtt的客户端 发布消息就往这个端口发。但是web 页面不一样,web页面是与9080端口交互, web页面发布消息是先发送到9080的web server上,然后再通过6000端口发送给订阅者。

var mosca = require('mosca');
var MqttServer = new mosca.Server({
    port: 6000,
    http: {
        port: 9080,
        bundle: true,
        static: './'
        }
});

MqttServer.on('ready', function(){
    console.log('mqtt is running...');
    //MqttServer.authenticate = authenticate;
});

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

MqttServer.on('clientDisconnected', function (client) {
    console.log('Client Disconnected     := ', client.id);
});


MqttServer.on('subscribed', function (topic, client) {
    console.log("Subscribed :=", topic, client.id);
});

MqttServer.on('unsubscribed', function (topic, client) {
    console.log('unsubscribed := ', topic, client.id);
});



MqttServer.on('published', function(packet, client) {
    
    if (typeof (client) == "undefined")
	return;

    else
	console.log('client ', client.id, ' publish :', 'topic ='+packet.topic+ ',message = '+ packet.payload.toString());

}); 


MqttServer.on("error", function (err) {
    console.log(err);
});

index.html源码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>
	<body>
		<input type="text" id="msg"/>
		<input type="button" value="订阅主题" onclick="subscribe()"/>
		<input type="button" value="发送消息" onclick="send()"/>
		<input type="button" value="取消订阅" onclick="unsubscribe()"/>
	</body>
	<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js"></script>
	
	<script>
		var hostname = '192.168.1.2',
		port = 9080,
		clientId = 'clientmao2080',
		timeout = 5,
		keepAlive = 50,
		cleanSession = false,
		ssl = false,
		userName = 'admin',
		password = 'password',
		topic = 'vulsun';
		client = new Paho.MQTT.Client(hostname, port, clientId); 
	
		var options = {
			invocationContext: {
				host : hostname,
				port: port,
				path: client.path,
				clientId: clientId
			},
			timeout: timeout, 
			keepAliveInterval: keepAlive, 
			cleanSession: cleanSession, 
			useSSL: ssl, 
			userName: userName,
			password: password,
			onSuccess: onConnect,
			onFailure: function(e){
				console.log(e);
			}
		};
		
		client.connect(options); 

		function onConnect() {
			console.log("onConnected");
			
		}
	
		client.onConnectionLost = onConnectionLost; 

		client.onMessageArrived = onMessageArrived; 

		function onConnectionLost(responseObject) {
			console.log(responseObject);
			if (responseObject.errorCode !== 0) {
				console.log("onConnectionLost:"+responseObject.errorMessage); 
				console.log("连接已断开"); 
			}
		} 
	
		function onMessageArrived(message) { 
			console.log("收到消息:"+message.payloadString); 
		} 
	
		function send(){
			var s = document.getElementById("msg").value;
			if(s.length > 0){

				message = new Paho.MQTT.Message(s);
				message.destinationName = topic;
				client.send(message);
				document.getElementById("msg").value = "";
				console.log("消息发送成功"+s);
			}
			else {
				alert("发送的消息不能为空");
			}
		}
	
		var count = 0;
	
		function subscribe(){
			client.subscribe(topic, { qos: 2});
			console.log("订阅主题:"+topic); 

		}
		
		function unsubscribe(){

			client.unsubscribe(topic);
			console.log("取消订阅主题:"+topic); 
		}
	
		
	</script>

</html>

这样就可以与服务器进行即时消息的交互了,并且没有跨域的问题。

可以用mosquitto_pub 发布消息进行测试

猜你喜欢

转载自blog.csdn.net/langeldep/article/details/82956992
今日推荐