Websocket 突破最大長連線

johnchou發表於2021-09-09

為了測試機器能夠最大的長連線個數,故寫了一個js指令碼,需要用node進行執行

var WebSocketClient = require('websocket').client; var size = 8000;
var index = 0;

setInterval(function () {
    if (index < size) {
        init();
        index++;
    }
}, 10);
console.log('begin...');
init = function () {
    var client = new WebSocketClient();
    let urlIndex = index;
    // client.connect('ws://192.168.214.191:8899/ws', "", "");
    client.connect('ws://127.0.0.1:21112/OrderWebSocket/'+index, "", "");
    // client.connect('ws://192.168.214.181:30004/Invest/OrderWebSocket/' + index, "", "");

    client.on('connectFailed', function (error) {
        console.log('Connect Error: ' + error.toString());
    });

    client.count = 0;

    client.start = 0;
    client.on('connect', function (connection) {
        var last = (Number)(new Date().getMilliseconds());
        console.log(index + ' Connectedn');
        connection.on('error', function (error) {
            console.log("Connection Error: " + error.toString());
        });
        connection.on('close', function (error) {
            var second = (new Date().getTime() - client.start)/1000 + 1; 
            console.log(error + ';  Connection Closed:second = '+ second +",count:"+client.count +"--timepercount:"+second/client.count);
            
        });
        connection.on('message', function (message) {
            if(client.start == 0){
                client.start = new Date().getTime();   
            }
            
            client.count++;
            // var now = (Number)(new Date().getMilliseconds());
            // // console.log("序號:"+urlIndex+",訊息:"+message.utf8Data+"n"+(now - last));
            // last = now;
        });
        connection.send("hello");
    });

}; 

以上程式碼就是來連線websocket使用的,發現到了1.3w左右連線,就出現Connection Error,解決方案


編輯/etc/security/limits.conf,新增以下兩行程式碼,注意前面有星號

* soft nofile 1000000
* hard nofile 1000000

圖片描述

然後修改臨時埠和IP_TABLE最大跟蹤的TCP連線數有限制,編輯/etc/sysctl.conf,在檔案中新增如下行

net.ipv4.ip_local_port_range = 10000 65535
net.netfilter.nf_conntrack_max = 1000000
net.nf_conntrack_max = 1000000

圖片描述

完畢,現在連線可以到4.5w左右差不多,我的機器會報以下錯誤
圖片描述

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/4422/viewspace-2824583/,如需轉載,請註明出處,否則將追究法律責任。

相關文章