如何设置最大值socket io 的客户端?

how to set max. of clients of socket io?

我的服务器只允许两个客户端连接。如何设置 socket.io 两个客户端的最大客户端数? 这是我的 server.js 的样子:

var path = require('path');
var express = require('express'),
    app = express(),
    http = require('http'),
    socketIo = require('socket.io');

var server = http.createServer(app);
var io = socketIo.listen(server);
server.listen(9000);

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname + 'index.html'));


});
app.use(express.static(__dirname + '/'));

io.on('connection', function (socket) {


    socket.on('data', function (data) {


        socket.broadcast.emit('data', data)
    });

    socket.on('disconnect', function () {
console.log("disconnect")
    });

});

这是未经测试的,但您应该能够检查连接上的用户数量并在 connect/disconnect 上更改它。

这是一个例子:

const connectedUsers = 0;
const maxUsers = 2;
io.on('connection', function (socket) {
    if(connectedUsers + 1 > maxUsers){ // check if the new connection will exceed the max connections allowed
       socket.disconnect(); // if so, disconnect the user and exit 
       return;
    }
    connectedUsers++; // otherwise + 1 to the connectedUsers
    socket.on('data', function (data) {
       socket.broadcast.emit('data', data)
    });
   socket.on('disconnect', function () {
       connecteUsers--; // on a disconnected decrease the connectedUsers count
       console.log("disconnect")
    });
});