Клиент:
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');
};
Сервер:
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);