mqtt mosca pahojs与'ws:// localhost:1884 / mqtt'的WebSocket连接失败/超时

时间:2015-06-28 10:57:18

标签: node.js mqtt paho

经纪人

var mosca = require('mosca')


var settings = {
  port: 1884
};

//here we start mosca
var server = new mosca.Server(settings);
server.on('ready', setup);

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

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

// fired when a message is received
server.on('published', function(packet, client) {
  if (packet.cmd === 'publish') {
    //Qui uso mongo DB 
    console.log('Published: ', packet.payload.toString('utf8'));
  }
});

// fired when a client subscribes to a topic
server.on('subscribed', function(topic, client) {
  console.log('subscribed : ', topic);
});

// fired when a client subscribes to a topic
server.on('unsubscribed', function(topic, client) {
  console.log('unsubscribed : ', topic);
});

// fired when a client is disconnecting
server.on('clientDisconnecting', function(client) {
  console.log('clientDisconnecting : ', client.id);
});

// fired when a client is disconnected
server.on('clientDisconnected', function(client) {
  console.log('clientDisconnected : ', client.id);
});

client.html

<html>
  <head>
        <meta charset="utf-8" />
  </head>
  <body>
    <script src="./mqttws3.1.js"></script>
      <script>
  var client = new Paho.MQTT.Client( 'localhost', 1884, 'clientId');

  client.onConnectionLost = onConnectionLost;
  client.onMessageArrived = onMessageArrived;
  client.connect({onSuccess:onConnect});

  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); 
};
function onConnectionLost(responseObject) {
  if (responseObject.errorCode !== 0)
  console.log("onConnectionLost:"+responseObject.errorMessage);
};
function onMessageArrived(message) {
  console.log("onMessageArrived:"+message.payloadString);
  client.disconnect(); 
};  
      </script> 
    </body>
</html>

我经营经纪人

node broker

比我通过Web服务器调用client.html 喜欢

http://localhost/client.html

我过了一会儿

  

Firefox无法与服务器建立连接   WS://本地主机:1884年/ MQTT。 this.socket = new WebSocket(wsurl,   [ “MQTT”]);

     

Chrome:与'ws:// localhost:1884 / mqtt'的WebSocket连接失败:   WebSocket打开握手超时

我不知道转向哪种方式:(

你能帮我吗?

1 个答案:

答案 0 :(得分:6)

看看这个:

https://github.com/mcollina/mosca/wiki/MQTT-over-Websockets

看起来你刚刚启动了一个普通的MQTT监听器而不是一个WS监听器。

您需要在设置中添加http块:

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