Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 连接nodejs和云mqtt_Javascript_Node.js_Mqtt_Iot - Fatal编程技术网

Javascript 连接nodejs和云mqtt

Javascript 连接nodejs和云mqtt,javascript,node.js,mqtt,iot,Javascript,Node.js,Mqtt,Iot,我正在做一个基于物联网的项目。所以我需要连接cloudmqtt和nodejs服务器 app.js // Create a MQTT Client var mqtt = require('mqtt'); // Create a client connection to CloudMQTT for live data var client = mqtt.connect('xxxxxxxxxxx', { username: 'xxxxx', password: 'xxxxxxx' });

我正在做一个基于物联网的项目。所以我需要连接
cloudmqtt
nodejs
服务器

app.js

// Create a MQTT Client
var mqtt = require('mqtt');

// Create a client connection to CloudMQTT for live data
var client = mqtt.connect('xxxxxxxxxxx', {
  username: 'xxxxx',
  password: 'xxxxxxx' 
});

client.on('connect', function() { // When connected
    console.log("Connected to CloudMQTT");
  // Subscribe to the temperature
  client.subscribe('Motion', function() {
    // When a message arrives, do something with it
    client.on('message', function(topic, message, packet) {
      // ** Need to pass message out **
    });
  });

});
var mqtt = require('mqtt');
var options = {
    port: 15255,
    host: 'mqtt://m11.cloudmqtt.com',
    clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
    username: 'xxxxxxxxxxxxxxxxxx',
    password: 'xxxxxxxxxxxxxxxxxx',
    keepalive: 60,
    reconnectPeriod: 1000,
    protocolId: 'MQIsdp',
    protocolVersion: 3,
    clean: true,
    encoding: 'utf8'
};
var client = mqtt.connect('mqtt://m11.cloudmqtt.com', options);
client.on('connect', function() { // When connected
    console.log('connected');
    // subscribe to a topic
    client.subscribe('topic1/#', function() {
        // when a message arrives, do something with it
        client.on('message', function(topic, message, packet) {
            console.log("Received '" + message + "' on '" + topic + "'");
        });
    });

    // publish a message to a topic
    client.publish('topic1/#', 'my message', function() {
        console.log("Message is published");
        client.end(); // Close the connection when published
    });
});

然后启动了我的服务器。但是什么也没有发生(没有错误消息和警告)。请帮我解决这个问题?

可能是连接出错,尝试添加这个,我想您会看到一些东西:

client.on('error', function(err) {
    console.log(err);
});

请检查启动/配置MQTT服务器的IP和端口是否打开。可能这两个被防病毒防火墙或服务器防火墙阻止,我没有得到你的访问端口。请在连接云mqtt之前检查这些服务器设置

activemq.xml and jetty.xml

    name="openwire" uri="tcp://0.0.0.0:61616 (default)
    name="amqp" uri="amqp://0.0.0.0:5672 (default)
    name="stomp" uri="stomp://0.0.0.0:61613 (default)
    name="mqtt" uri="mqtt://0.0.0.0:1883 (default) (Android and Ios team)
    name="ws" uri="ws://0.0.0.0:61614 (default) (Php team)
访问url mqtt:

请关注物联网核心 如果您正在使用Node.js构建应用程序,则有Mosca()

如果您正在使用Python构建应用程序,那么可以查看hbmqtt()

开发者端代码共享,可能会有帮助:

if (!window.WebSocket) {
    $("#connect").html("\

            <p>\
            Your browser does not support WebSockets. This example will not work properly.<br>\
            Please use a Web Browser with WebSockets support (WebKit or Google Chrome).\
            </p>\
        ");
} else {
    function subscribeClient() {
        var currentDate = new Date();
        var mqtt_clientId = CURRENT_USER_ID + "-" + currentDate.getTime();     
        var mqtt_host = '00.000.00.000';
        var mqtt_port = '00000';
        var mqtt_user = 'xxxxx';
        var mqtt_password = 'xxxxx';
        $("#connect_clientId").val("example-" + (Math.floor(Math.random() * 100000)));
        var timeout = 3000 / 2;
        var keepAliveInterval = 3000;
        var maxMqqtConnectCount = 80;
        client = new Messaging.Client(mqtt_host, Number(mqtt_port), mqtt_clientId);
        client.onConnect = onConnect;
        client.onMessageArrived = onMessageArrived;
        client.onConnectionLost = onConnectionLost;
        // the client is notified when it is connected to the server.
        var onConnect = function (frame) {
            console.log('mqqt connected.');
            $("#chat_conn").val(1);
            $(".offline-alert").css("display", "none");
            // connecting client
            client.subscribe(topicId);
            //subscribing to multiple groups
            var groups = JSON.parse($("#current_user_groups").val());
            $(groups).each(function (index, element) {
                var group_id = element["GroupID"];
                var group_topic_id = getGroupTopicId(group_id);
                client.subscribe(group_topic_id);
            });

        };

        function disconnectClient() {
            client.disconnect();
            $(".offline-alert").css("display", "block");
            $("#chat_conn").val(0);
        }

        function onFailure(failure) {
            console.log('mqqt connectinn failed');
            $("#chat_conn").val(0);
            $(".offline-alert").css("display", "block");
            connectMqtt();
        }

        function onConnectionLost(responseObject) {
            console.log('mqqt connectinn lost');
            $("#chat_conn").val(0);
            $(".offline-alert").css("display", "block");
            connectMqtt();
        }

        function onMessageArrived(message) {
            if (!message) {
                return false;
            }
            console.log(message.payloadString);

            }


        function connectMqtt()
        {
            var currentConnectionCount = getMqqtConnectionLostCount();
            if (currentConnectionCount <= maxMqqtConnectCount)
            {
                setMqqtConnectionLostCount();
                console.log('connecting mqqt ' + getMqqtConnectionLostCount() + ' times.');
                client.connect({
                    timeout: timeout, //seconds
                    keepAliveInterval: keepAliveInterval,
                    userName: mqtt_user,
                    useSSL: false, // for secure connection on https #added by Virendra Yadav ver1.1 on 2015-02-03 to set MQTT SSL use setting
                    password: mqtt_password,
                    onSuccess: onConnect,
                    onFailure: onFailure,
                });
            } else
            {

                console.log('mqqt unable to connect more than ' + maxMqqtConnectCount + ' times.');
                window.location.reload();
            }
        }
        connectMqtt();

        function setMqqtConnectionLostCount()
        {
            var currentConnectionLostCount = getMqqtConnectionLostCount();
            currentConnectionLostCount = parseInt(currentConnectionLostCount);
            currentConnectionLostCount = currentConnectionLostCount + 1;
            $('#mqqtReconnectConnectionCount').val(currentConnectionLostCount);
        }
        function getMqqtConnectionLostCount()
        {
            var countVal = $('#mqqtReconnectConnectionCount').val();
            return countVal;
        }
    }
if(!window.WebSocket){
$(“#连接”).html\
\
您的浏览器不支持WebSocket。此示例无法正常工作。
\ 请使用支持WebSocket的Web浏览器(WebKit或Google Chrome)\

\ "); }否则{ 函数subscribeClient(){ var currentDate=新日期(); var mqtt_clientId=CURRENT_USER_ID+“-”+currentDate.getTime(); var mqtt_host='00.000.00.000'; var mqtt_端口='00000'; var mqtt_user='xxxxx'; var mqtt_password='xxxxx'; $(“#connect_clientId”).val(“示例-”+(Math.floor(Math.random()*100000)); var超时=3000/2; var keepAliveInterval=3000; var maxmqtconnectcount=80; client=new Messaging.client(mqtt_主机,编号(mqtt_端口),mqtt_客户端ID); client.onConnect=onConnect; client.onMessageArrived=onMessageArrived; client.onConnectionLost=onConnectionLost; //客户端连接到服务器时会收到通知。 var onConnect=功能(帧){ log('mqqt已连接'); $(“chat#u conn”).val(1); $(“.offline alert”).css(“显示”、“无”); //连接客户端 客户。订阅(topicId); //订阅多个组 var groups=JSON.parse($(“#当前_用户_组”).val(); $(组)。每个(函数(索引、元素){ var group_id=元素[“GroupID”]; var group\u topic\u id=getGroupTopicId(group\u id); client.subscribe(组\主题\ id); }); }; 函数disconnectClient(){ client.disconnect(); $(“.offline alert”).css(“显示”、“阻止”); $(“chat#u conn”).val(0); } 功能失效(失效){ log('mqqt connectinn failed'); $(“chat#u conn”).val(0); $(“.offline alert”).css(“显示”、“阻止”); connectMqtt(); } 函数onConnectionLost(响应对象){ log('mqqt connectinn lost'); $(“chat#u conn”).val(0); $(“.offline alert”).css(“显示”、“阻止”); connectMqtt(); } 函数onMessageArrived(消息){ 如果(!消息){ 返回false; } console.log(message.payloadString); } 函数connectMqtt() { var currentConnectionCount=getMqqtConnectionLostCount();
如果(currentConnectionCount我已经实现了云MQTT和NodeJs接口


    var mqtt = require('mqtt'),url = require('url')
    var client = mqtt.createClient(PORTNO,"m10.cloudmqtt.com",
    {
        username: "xxxxxxxxx",
        password: "xxxxxxxxx"
    });

    client.on('connect',function()
    {
        client.publish("Hello",function()
        {
            client.end();
        })
    })
    

现在,
cloudmqtt
nodejs
服务器通过提供诸如clientId、keepalive、protocolVersion等额外参数进行连接

app.js

// Create a MQTT Client
var mqtt = require('mqtt');

// Create a client connection to CloudMQTT for live data
var client = mqtt.connect('xxxxxxxxxxx', {
  username: 'xxxxx',
  password: 'xxxxxxx' 
});

client.on('connect', function() { // When connected
    console.log("Connected to CloudMQTT");
  // Subscribe to the temperature
  client.subscribe('Motion', function() {
    // When a message arrives, do something with it
    client.on('message', function(topic, message, packet) {
      // ** Need to pass message out **
    });
  });

});
var mqtt = require('mqtt');
var options = {
    port: 15255,
    host: 'mqtt://m11.cloudmqtt.com',
    clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
    username: 'xxxxxxxxxxxxxxxxxx',
    password: 'xxxxxxxxxxxxxxxxxx',
    keepalive: 60,
    reconnectPeriod: 1000,
    protocolId: 'MQIsdp',
    protocolVersion: 3,
    clean: true,
    encoding: 'utf8'
};
var client = mqtt.connect('mqtt://m11.cloudmqtt.com', options);
client.on('connect', function() { // When connected
    console.log('connected');
    // subscribe to a topic
    client.subscribe('topic1/#', function() {
        // when a message arrives, do something with it
        client.on('message', function(topic, message, packet) {
            console.log("Received '" + message + "' on '" + topic + "'");
        });
    });

    // publish a message to a topic
    client.publish('topic1/#', 'my message', function() {
        console.log("Message is published");
        client.end(); // Close the connection when published
    });
});

请注意,密码是一个缓冲区,您可以传递选项上的任何属性:

var options = { username: 'strUserName',
                password: new Buffer('strPassword')};

var client = mqtt.connect('mqtt://m11.cloudmqtt.com', options);

感谢您的快速响应。我已经添加了这行代码。但是同样的事情再次发生。您有任何示例吗?感谢您的快速响应。我从哪里得到这个文件?请检查您的conf文件夹..\apache-activemq-5.11.1\conf以及防火墙设置开放端口或IP的入站和出站答案不应该都是代码块,请重新选择把它垫起来,这样它就可读了。这不像,我在提供解决方案!!据我所知,我在尝试帮助这个男孩。不要再这样评论了。现在不行。使用这个解决方案有什么问题吗?我试过了,但总是出错-失败:在WebSocket握手时出错:net::ERR\u连接_RESET@Muhsin我有一个我在这里通过几个谷歌搜索。也许你可以给我一些指导。我正在从我的javascript客户端连接到mqtt,并从javascript设置用户名/密码作为示例。但是你知道从浏览器检查这些凭据非常简单。你如何防止这种情况?或者可能有一些不同的“安全”解决方案从浏览器连接到mqtt?如果任何人在连接到Cloudmqtt Websockets API时仍遇到此问题,并且出现连接重置错误,请将主机更改为
wss://soldier.cloudmqtt.com:38190/mqtt
相应地更改URL和端口。