Created
February 5, 2018 19:00
-
-
Save diaz-de-berenguer/2aa52ce776ad42a55759ca7c8afe777e to your computer and use it in GitHub Desktop.
Removing a User from an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Define WebSocket using ws library | |
const WebSocket = require('ws'); | |
// Initialise wss as a new Websocket Server running in port 8989 | |
const wss = new WebSocket.Server({ port: 8989 }); | |
// Array of users currently logged in. Serves as the Database. | |
var users = []; | |
// This is the code that will run on the server when a new client is connected to | |
// the web socket server. | |
wss.on('connection', (ws) => { | |
// Random number | |
let userId = Math.floor(Math.random() * 10**10); | |
// .... | |
// rest of the code here | |
// .... | |
// When we add the new user to the array of users, use userId | |
users.push({ | |
name: data.name, | |
id: userId | |
}); | |
// ... | |
// When the connection is closed, remove the user with userId | |
ws.on('close', () => { | |
// Remove User from 'database' | |
users = users.filter( (u) => { | |
return u.id !== userId | |
}); | |
// Send updated user list to all the connected users | |
broadcast({ | |
type: 'USERS_LIST', | |
users | |
}, ws); | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment