Created
September 15, 2021 04:39
-
-
Save nokotan/42d9d43c93099232ca8f3d58ba517a7a to your computer and use it in GitHub Desktop.
WebSocket Server
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
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