mqtt mosca pahojs WebSocket 连接到 'ws://localhost:1884/mqtt' failed/timeout

mqtt mosca pahojs WebSocket connection to 'ws://localhost:1884/mqtt' failed/timeout

经纪人

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

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

http://localhost/client.html

过一会儿我就搞定了

Firefox can't establish a connection to the server at ws://localhost:1884/mqtt. this.socket = new WebSocket(wsurl, ["mqtt"]);

Chrome : WebSocket connection to 'ws://localhost:1884/mqtt' failed: WebSocket opening handshake timed out

我不知道该往哪个方向转:(

你能帮帮我吗?

看看这个:

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

您似乎刚刚启动了一个普通的 MQTT 侦听器,而不是 WS 侦听器。

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

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