V
V
Vladimir2019-04-20 06:40:02
Socket.io
Vladimir, 2019-04-20 06:40:02

There is a counter of socket.io clients on the server, clients are added but they are not reduced when disconnected, what should I do?

Customer:

var host = 'http://localhost:3000/';
var socket = io(host);
var hp = 10000;
      		
document.querySelector('.send').addEventListener('click', ev => {
  ev.preventDefault();
      			
  let text = document.querySelector('.input').value;     		
  hp = hp-100;
 		if(hp <= 0) hp = 0;
     socket.emit('message',hp);
      		
});	

socket.emit('forceDisconnect');

socket.on('new message', function(data) {
  hp = data;
  let li = document.createElement('li');
  li.textContent = hp;
      			
  document.querySelector('body').appendChild(li);
});
      	       	 
socket.on('disconnect', function(data) {
  alert('Сервер заполнен'); 
 // window.location.replace(host + 'serverfull');
});

window.onbeforeunload = function() { 
  return "Данные не сохранены. Точно перейти?";
  socket.disconnect(true);
  socket.emit('forceDisconnect');
};

Server:
var express = require('express'); // Get the module 
var app = express(); // Create express by calling the prototype in var express
var http = require('http').Server(app);
var connections=0,max_connections=2,port = 3000;

let io = require('socket.io')(http);

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

app.get('/go', function(req,res) {
  res.sendFile(__dirname + '/client/public/index.html');
});
app.get('/boss', function(req,res) {
  res.sendFile(__dirname + '/client/boss.html');
});

http.listen(port, function() {
  console.log('listening on *:' + port);
});

io.on('connection', function(socket) {
  console.log('connected new client');
      
      connections+=1;
      
      if(connections > max_connections) {
        connections-=1;
        socket.on('forceDisconnect', function(data){
          socket.disconnect(true);
          console.log('Server full!');
        });
      }
      
      console.log(connections);
      
      socket.on('message', function(data) {
   			io.emit('new message', data);
   	});
   	
   	
   	
});
console.log(connections);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2019-04-20
@HistoryART

This is how the solution looks like, forceDisconnect - disconnects the client, socket.on disconnect, keeps a counter, thanks for the help guys.

connections+=1;
      
      if(connections > max_connections) {
        connections-=1;
        socket.on('forceDisconnect', () => {
            socket.disconnect(true);
            console.log('Server full!');
        });
      }
      
      socket.on( 'disconnect', () => { 
        connections -= 1; 
        console.log( 'client disconnected' ) ;
        
      });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question