Created
December 16, 2019 23:30
-
-
Save dragonwocky/832c1bc1cfb19f5efb1cd70b7364d66f to your computer and use it in GitHub Desktop.
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
const wss = new ws.Server({ server: server }); | |
_.broadcast = (data, room) => { | |
wss.clients.forEach(client => { | |
if (client.readyState === ws.OPEN) { | |
if (!room || client.room === room) | |
client.send(JSON.stringify(data), error => { | |
if (error) console.log(error); | |
}); | |
} | |
}); | |
}; | |
_.users = 0; | |
wss.on('connection', (socket, req) => { | |
socket.parse = content => socket.send(JSON.stringify(content)); | |
socket.on('message', msg => { | |
msg = JSON.parse(msg); | |
console.log(msg); | |
switch (msg.type) { | |
case 'setup': | |
/** | |
* { | |
* type: 'setup', | |
* data: { | |
* name: String, | |
* room: String | |
* } | |
* } | |
*/ | |
if (!msg.data.name) break; | |
socket._name = msg.data.name; | |
socket._room = msg.data.room; | |
socket._uid = _.users++; | |
socket.parse({ type: 'id', data: { uid: socket._uid } }); | |
_.broadcast( | |
{ | |
type: 'join', | |
data: { | |
name: socket._name, | |
uid: socket._uid | |
} | |
}, | |
socket._room | |
); | |
break; | |
case 'message': | |
/** | |
* { | |
* type: 'message', | |
* data: { | |
* text: String, | |
* time: Date | |
* } | |
* } | |
*/ | |
if (!msg.data.text || !msg.data.time) break; | |
_.broadcast( | |
{ | |
type: 'message', | |
data: { | |
name: socket._name, | |
uid: socket._uid, | |
text: msg.data.text, | |
time: new Date(msg.data.time).toUTCString(), | |
msgID: uuidv4() | |
} | |
}, | |
socket._room | |
); | |
} | |
}); | |
socket.on('close', () => { | |
if (socket._name && socket._uid && socket._room) | |
_.broadcast( | |
{ | |
type: 'leave', | |
data: { | |
name: socket._name, | |
uid: socket._uid | |
} | |
}, | |
socket._room | |
); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment