Skip to content

Instantly share code, notes, and snippets.

@Zwiterrion
Created March 7, 2024 08:04
Show Gist options
  • Save Zwiterrion/8a3d107aba8762dea9db4fa624292ed3 to your computer and use it in GitHub Desktop.
Save Zwiterrion/8a3d107aba8762dea9db4fa624292ed3 to your computer and use it in GitHub Desktop.
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