-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
97 lines (81 loc) · 2.5 KB
/
Copy pathindex.js
File metadata and controls
97 lines (81 loc) · 2.5 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
'use strict'
const WebSocket = require('ws')
const standardSettings = require('standard-settings')
const settings = standardSettings.getSettings()
const { v1: uuid } = require('uuid')
const ip = require('ip')
const port = settings.port || 9375
const selfBroadcast = settings.selfBroadcast || false
const wss = new WebSocket.Server({
port,
perMessageDeflate: false
})
wss.on('listening', function listening () {
console.log(`spacebro listening on ws://${ip.address()}:${wss.options.port} ...`)
})
wss.on('close', function close () {
for (const client of wss.clients) {
client.close()
}
})
wss.on('connection', function connection (ws, req) {
// console.log(req.url)
// console.log(req.headers.host)
// console.log(req.connection)
// const query = url.parse(req.url, true).query
const query = new URL(req.url, `ws://${req.headers.host}/`).searchParams
// console.log(query)
ws.name = query.get('name') || uuid()
console.log(`${ws.name} is opened.`)
ws.on('message', function incoming (raw) {
let data = {}
try {
data = JSON.parse(raw)
console.log(`received event from ${ws.name} to ${data.to || 'default'}`)
} catch (err) {
console.error('malformed JSON')
if (typeof raw === 'string') {
console.log('try to use the raw event as EventName')
data.eventName = raw
}
console.log(raw)
}
const nameLog = data.eventName || '(no eventName prop found)'
const propsLog = data.hasOwnProperty('data') ? `has props {${Object.keys(data.data)}}` : ''
console.log(`event "${nameLog}" ${propsLog}`)
if (data.to && data.to !== 'default') {
for (const client of wss.clients) {
if (client.name === data.to) {
send(client, data, ws.name)
}
}
} else {
wss.clients.forEach((client) => {
if ((client !== ws || selfBroadcast)) {
send(client, data, ws.name)
}
})
}
})
ws.on('close', function closing (code) {
console.log(`${ws.name} is closed.`)
})
send(ws, { eventName: 'connected', data: `connected with id ${ws.name}` }, 'server')
})
function send (client, data, name) {
if (client.readyState === WebSocket.OPEN) {
try {
const payload = JSON.stringify({ ...data, from: name })
client.send(payload)
} catch (e) {
console.log(e)
}
}
}
process.on('SIGINT', onAppExit)
process.on('SIGQUIT', onAppExit)
process.on('SIGTERM', onAppExit)
async function onAppExit () {
console.log('\nsending close event.')
await wss.close()
}