I make the simplest chat server on nodejs and websockets (ws). And it is impossible to implement the processing of closing, when the user closes the browser / tab, although everything seems to be following the instructions.

For some reason, all connections are closed at once, and sometimes the server drops. What is wrong here?

var Server = require('ws').Server; var port = process.env.PORT || 9030; var wss = new Server({port: port}); var users = []; wss.broadcast = function(data, self) { for (var i in this.clients) { if (this.clients[i] !== self) { this.clients[i].send(data); } } }; function noop() {} function heartbeat() { this.isAlive = true; } wss.on('connection', function(ws) { ws.isAlive = true; ws.on('pong', heartbeat); ws.on('message', function(message) { var msg = JSON.parse(message); if (msg.type === 'hello') { // ДобавляСм Π² массив Π½ΠΈΠΊ ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡ΠΈΠ²ΡˆΠ΅Π³ΠΎΡΡ // ΠΈ отправляСм Π΅ΠΌΡƒ Π½ΠΈΠΊΠΈ ΠΏΠΎΠ΄ΠΊΠ»ΡŽΡ‡Ρ‘Π½Π½Ρ‹Ρ…, ΠΎΡΡ‚Π°Π»ΡŒΠ½Ρ‹ΠΌ β€” Π΅Π³ΠΎ Π½ΠΈΠΊ users.push([msg.nickname, ws]) var hello_reply = {"type": "hello", "clients": "user1", "user2"}; var user_connected = {"type": "connected", "nickname": msg.nickname}; wss.broadcast(JSON.stringify(user_connected), ws); ws.send(JSON.stringify(hello_reply)); } }); const interval = setInterval(function ping() { wss.clients.forEach(function each(ws) { // удаляСм ΠΈΠ· массива Π½ΠΈΠΊΠΎΠ² имя ΡƒΡˆΠ΅Π΄ΡˆΠ΅Π³ΠΎ // ΠΈ отправляСм Π΅Π³ΠΎ имя всСм if (ws.isAlive === false) { for (var i in users) { if (users[i][1] === ws) users.splice(i, 1); } var user_disconnected = {"type": "message", "text": "He"}; wss.broadcast(JSON.stringify(user_disconnected), ws); return ws.terminate(); } ws.isAlive = false; ws.ping(noop); }); }, 30000); 

    0