1

经纪人

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);
});

客户端.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 无法与位于 ws://localhost:1884/mqtt 的服务器建立连接。this.socket = new WebSocket(wsurl, ["mqtt"]);

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

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

你能帮我吗 ?

4

1 回答 1

6

看看这个:

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

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

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

var settings = {
  http: {
    port: 1884,
    bundle: true,
    static: './'
  }
};
于 2015-06-28T12:21:54.637 回答