mqtt服务器采用activemq实现。
首先配置activemq支持websocket.
具体配置,请点击activemq官网配置。
编写客户端页面,引入Paho官方客户端js库。
具体配置,请点击查看
贴出关键代码如下:
// Create a client instance //注意不要在client前写var client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId"); // 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("World"); message = new Paho.MQTT.Message("Hello"); message.destinationName = "World"; 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); }
注意不要在client前写var
否则你可能会出现一下错误:
https://www.eclipse.org/forums/index.php/t/1068818/