Set up server to relay ripples and presence info

This commit is contained in:
arne 2024-01-27 12:04:46 +01:00
commit 8ccb60de61
7 changed files with 338 additions and 7 deletions

65
server/index.ts Normal file
View file

@ -0,0 +1,65 @@
import { type ServerWebSocket } from "bun"
type WebsocketData = {
clientId: string
}
type Message =
| { type: 'presence-information', others: number }
| { type: 'ripple', position: [number, number], maxRadius: number }
const clients: Map<WebsocketData['clientId'], ServerWebSocket<WebsocketData>> = new Map()
const server = Bun.serve<WebsocketData>({
fetch(req, server) {
// TODO Allow creating private ponds
server.upgrade(req, {
data: {
clientId: crypto.randomUUID()
}
})
},
websocket: {
open(ws) {
// register newly connected client and tell them how many other people are there
console.log('Connection opened', ws.data.clientId)
clients.set(ws.data.clientId, ws)
const enterNotice = JSON.stringify(<Message>{
type: 'presence-information',
others: clients.size,
})
for (const [uuid, client] of clients.entries()) {
if (uuid !== ws.data.clientId) {
client.send(enterNotice, true)
}
}
},
message(ws, message) {
// broadcast message to all other clients
// TODO: Validate message shape
const msg = JSON.parse(`${message}`)
console.log('Relaying message from', ws.data.clientId, msg)
for (const [uuid, client] of clients.entries()) {
if (uuid !== ws.data.clientId) {
client.send(message)
}
}
},
close(ws, code, reason) {
// remove client from list of registered clients and tell other clients how many people are there
console.log('Connection closed', ws.data.clientId)
clients.delete(ws.data.clientId)
const leaveNotice = JSON.stringify(<Message>{
type: 'presence-information',
others: clients.size,
})
for (const [uuid, client] of clients.entries()) {
if (uuid !== ws.data.clientId) {
client.send(leaveNotice, true)
}
}
}
},
})
console.log(`Server running on ${server.hostname}:${server.port}`)