2

to my server are just two clients allowed to connect with. How to set the max of clients on two clients of socket.io? this is how my server.js looks like:

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

});

1 Answers1

0

This is untested, but you should be able to check number of users on connection and change it on connect/disconnect.

Here is an example:

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 https://stackoverflow.com/a/5560187/11518920
       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")
    });
});
JamesBot
  • 131
  • 1
  • 2
  • 8
  • thanks, is there any trick how to show an alert to the third user that he cannot connect to the server ? –  Jun 11 '19 at 19:21
  • @GermanyDeutschland Before calling the disconnect function, just send a message to that specific user. – JamesBot Jun 12 '19 at 00:05
  • Yes but how to send the message ? –  Jun 12 '19 at 07:03