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

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://localhost:1884/mqtt でサーバーへの接続を確立できません。this.socket = new WebSocket(wsurl, ["mqtt"]);

Chrome: 'ws://localhost:1884/mqtt' への WebSocket 接続に失敗しました: WebSocket を開くハンドシェイクがタイムアウトしました

どっちに転ぶかわからない(笑)

私を助けてくれませんか?

4

1 に答える 1