Вот ответ
Клиент:
var host = 'http://localhost:3000/',socket = io(host),hp,hp2,connections,x;
$('.boss').click(function() {
socket.emit('damage',54397);
$('.hp-line').css("width", x+'%');
});
socket.emit('hp line for all');
socket.emit('forceDisconnect');
socket.on('connections', function(data) {
connections = data;
$('.users-count').html(connections);
});
socket.on('realtime hp', function(data) {
hp = data;
$('.hp-line').html(hp);
});
$('.hp-line').html(hp);
socket.on('disconnect', function(data) {
alert('Сервер заполнен');
// window.location.replace(host + 'serverfull');
});
socket.on('hp line width', function(data) {
x = data;
$('.hp-line').css("width", x+'%');
});
window.onbeforeunload = function() {
//return "Данные не сохранены. Точно перейти?";
};
Сервер:
var app = express();
var http = require('http').Server(app);
var connections=0,max_connections=2,port = 3000,maxhp = 300000,hp = maxhp,x;
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');
});
http.listen(port, function() {
console.log('listening on *:' + port);
});
io.on('connection', function(socket) {
connections+=1;
io.emit('connections', connections);
console.log('connected client:' + connections);
if(connections > max_connections) {
socket.on('forceDisconnect', () => {
socket.disconnect(true);
console.log('Server full!' + max_connections + '/' + max_connections);
});
}
socket.on( 'disconnect', () => {
connections -= 1;
console.log( 'client disconnected:' + connections);
io.emit('connections', connections);
});
socket.on('damage', function(data) {
hp = hp-data;
if(hp<=0) hp = maxhp;
x = hp/maxhp*100;
io.emit('realtime hp', hp);
if(hp>0) io.emit('hp line width', x);
if(hp<=0) io.emit('hp line width', 0);
console.log(hp);
});
socket.on('hp line for all', function(data) {
x = hp/maxhp*100;
io.emit('realtime hp', hp);
io.emit('hp line width', x);
if(hp<=0) io.emit('hp line width', 0);
});
});
var express = require('express');