You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
1.7 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

const WebSocket = require('ws')
const wss = new WebSocket.Server({ noServer: true, clientTracking: true })
let vvvv = null
const connections = new Map()
// Dynamic message processor
const messageProcessor = {
hello_v4: (ws, msg) => registerV4(ws),
new_user: (ws, msg) => newUser(ws, msg),
default: (ws, msg) => unknownMsg(msg),
ui_counter: (ws, msg) => uiCounter(msg),
}
const registerV4 = (ws, msg) => {
console.log('⬛ vvvv client connected')
vvvv = ws
// if (vvvv?.readyState === WebSocket.OPEN) {
// vvvv.send(JSON.stringify(connections))
// }
}
const newUser = (ws, msg) => {
console.log(`👤 New user connected: ${msg.user}`)
ws.user = msg.user
connections.set(msg.id, ws)
if (vvvv?.readyState === WebSocket.OPEN) {
vvvv.send(JSON.stringify(msg))
}
}
const unknownMsg = (msg) => {
console.log('❔Unknown message type...')
console.log(msg)
}
// Interaction messsages
const uiCounter = (msg) => {
console.log(` Counter Interaction: +1 from ${connections.get(msg.id).user}`)
if (vvvv?.readyState === WebSocket.OPEN) {
vvvv.send(JSON.stringify(msg))
}
}
// Websocket Events
wss.on('connection', (ws) => {
ws.on('message', (data) => {
let message
try {
message = JSON.parse(data)
} catch (e) {}
if (message) {
;(messageProcessor[message.type] || messageProcessor.default)(ws, message)
}
})
ws.on('close', () => {
// console.log('Client Disconnected')
})
})
// Upgrade connection
export default function () {
this.nuxt.hook('listen', (server) => {
server.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws)
})
})
})
}