Created
March 7, 2024 08:04
-
-
Save Zwiterrion/8a3d107aba8762dea9db4fa624292ed3 to your computer and use it in GitHub Desktop.
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
const { WebSocketServer } = require('ws'); | |
const ws = new WebSocketServer({ port: 4444 }); | |
let clients = [] | |
ws.on('connection', (ws, req) => { | |
const parts = req.url.split('/'); | |
const name = parts[parts.length - 1].trim(); | |
clients.push({ ws, name }); | |
ws.send(`Welcome ${name}!`); | |
ws.on('close', () => { | |
clients = clients.filter(client => client.name !== name); | |
}); | |
ws.on('error', console.error); | |
ws.on('message', data => { | |
clients | |
.filter(client => client.name !== name) | |
.forEach(client => client.ws.send(data)); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment