Node.js 搭建mqttServer 及 mqttClient

Node.js在webStorm下进行编码测试

1、服务器端源码

/**
 * Created by niyl on 2016/1/13.
 */

var mosca = require('mosca');
var MqttServer = new mosca.Server({
    port: 1883
});

MqttServer.on('clientConnected', function(client){
    console.log('client connected', client.id);
});

/**
 * 监听MQTT主题消息
 **/
MqttServer.on('published', function(packet, client) {
    var topic = packet.topic;
    console.log('message-arrived--->','topic ='+topic+',message = '+ packet.payload.toString());

});

MqttServer.on('ready', function(){
    console.log('mqtt is running...');
    //MqttServer.authenticate = authenticate;
});

2、客户端源码

/**
 * Created by Administrator on 2016/1/13.
 */

var mqtt  = require('mqtt');
//var client  = mqtt.connect('mqtt://test.mosca.io');
//var client  = mqtt.connect('mqtt://192.168.103.237');
//var client  = mqtt.connect('mqtt://m2m.vicbang.com',{
//    username:'13800000000',
//    password:'123456',
//    clientId:'app_13800000000'
//});

for(var i = 0; i <2000;i++){
    var client  = mqtt.connect('mqtt://localhost',{
        username:'username',
        password:'password',
        clientId:'app_13800000000_'+i
    });

    client.on('connect', function () {
        console.log('connected.....');
        client.subscribe('#');
        client.publish('app2dev/', 'Hello mqtt');
    });

    client.on('message', function (topic, message) {
        // message is Buffer
        console.log(message.toString());
        //client.end();
    });
}

客户端的代码进行了2000次连接发送消息。电脑window7系统,内存4G,服务器端和客户端都在webStorm环境下运行,2000次没有一点儿压力。

再copy一份客户端源码,对clientid稍作修改,再次进行并发连接测试,发现cpu爆满,客户端程序停止连接。

分析一下,如果电脑只跑服务端程序,在其他电脑上跑客户端程序,并发连接数会更大一些。

你可能感兴趣的:(Node.js,MQTT,Server,Client)