-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (61 loc) · 1.48 KB
/
index.js
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
'use strict'
const WebSocket = require('ws')
const defaults = {
host: '127.0.0.1',
port: 9375,
autoReconnect: true
}
const events = []
let ws = null
let reconnectTimeout = null
function setup (options) {
const opt = {...defaults, ...options}
const queries = opt.name ? `name=${opt.name}` : ''
ws = new WebSocket(`ws://${opt.host}:${opt.port}/?${queries}`)
ws.on('open', function open () {
clearTimeout(reconnectTimeout)
})
ws.on('message', function incoming (raw) {
let eventName = 'default'
let data = null
let from = 'none'
try {
const obj = JSON.parse(raw)
eventName = obj.eventName
data = obj.data
from = obj.from
} catch (e) {
data = raw
}
console.log('---')
console.log(`event ${eventName} from ${from}`)
console.log(data)
if (typeof events[eventName] === 'function') {
events[eventName](data, from)
}
})
ws.on('error', function error (error) {
// console.log(error)
})
ws.on('close', function closing (code) {
console.log('socket closed')
if (opt.autoReconnect) {
reconnectTimeout = setTimeout(() => {
console.log('reconnecting...')
setup(opt)
}, 500)
}
})
}
function emit (eventName, data, to) {
try {
const payload = JSON.stringify({ eventName, data, to })
ws.send(payload)
} catch (e) {
console.log(e)
}
}
function on (eventName, callback) {
events[eventName] = callback
}
module.exports = { setup, emit, on }