This repository was archived by the owner on Aug 31, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebsocket.js
More file actions
52 lines (45 loc) · 1.28 KB
/
websocket.js
File metadata and controls
52 lines (45 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
'use strict'
var WebSocketServer = require('ws').Server
module.exports = (server) => {
var wss = new WebSocketServer({ server: server })
wss.broadcast = function (data) {
wss.clients.forEach(function (client) {
client.send(data)
})
}
wss.isUsernameAvailable = function (str) {
if (!str || typeof str !== 'string') return false
for (let client of wss.clients) {
if (new RegExp('^' + client.username + '$', 'i').test(str)) return false
}
return true
}
wss.on('connection', function (socket) {
socket.on('message', function (message) {
try {
message = JSON.parse(message)
} catch (e) {
console.log(e.message)
}
switch (message.type) {
case 'login':
if (wss.isUsernameAvailable(message.data)) {
socket.username = message.data
socket.send('loginSuccess')
wss.broadcast('@' + message.data + ' logged in.')
} else {
socket.send('loginFailed')
}
break
case 'message':
wss.broadcast('@' + socket.username + ': ' + message.data)
break
}
})
socket.on('close', function () {
if (socket.username) {
wss.broadcast('@' + socket.username + ' logged out.')
}
})
})
}