Skip to content

Instantly share code, notes, and snippets.

@nokotan
Created September 15, 2021 04:39
Show Gist options
  • Save nokotan/42d9d43c93099232ca8f3d58ba517a7a to your computer and use it in GitHub Desktop.
Save nokotan/42d9d43c93099232ca8f3d58ba517a7a to your computer and use it in GitHub Desktop.
WebSocket Server
import WebSocket, { Server } from 'ws';
const wss = new Server({ port: 28080 });
let uniqueID = 0;
let clients: WebSocket[] = [];
wss.on('connection', function connection(ws) {
const clientId = uniqueID++;
clients.push(ws);
console.log('connected');
ws.on('message', function incoming(message) {
clients
.filter(x => x !== ws)
.forEach(x => {
const data = JSON.parse(message.toString());
x.send(JSON.stringify({
type: 'updatePos',
playerId: clientId,
...data
}) + '\n');
})
});
ws.on('close', function onClose() {
clients
.filter(x => x !== ws)
.forEach(x => {
const data = {
type: 'removeId',
playerId: clientId
};
x.send(JSON.stringify(data) + '\n');
});
delete clients[clients.findIndex(x => x === ws)];
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment