-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
94 lines (79 loc) · 1.76 KB
/
app.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const fs = require('fs');
const Koa = require('koa');
const Router = require('koa-router');
const websockify = require('koa-websocket')
const uuidv4 = require('uuid/v4')
const app = new Koa();
const router = new Router();
const wsRouter = new Router();
let CONN = {}
function addConnection(id, uuid, ws) {
if (!CONN[id]) {
CONN[id] = {
[uuid]: ws
}
} else if (!CONN[id][uuid]) {
CONN[id][uuid] = ws
}
}
function removeConnection(id, uuid) {
if (CONN[id]) {
CONN[id][uuid] = null
delete CONN[id][uuid]
}
}
function okRes(data){
return JSON.stringify({
code: 0,
msg: 'ok',
data: data
})
}
function errRes(code, msg) {
return JSON.stringify({
code: code,
msg: msg
})
}
router.get('/', function(ctx, next){
ctx.body = 'It works!'
})
router.get('/collect', function(ctx, next){
const id = ctx.request.query.id
const msg = ctx.request.query.msg
if(CONN[id]) {
Object.keys(CONN[id]).forEach((key) => {
CONN[id][key].send(msg)
})
}
ctx.body = okRes({
success: true
})
})
router.get('/show', function(ctx, next){
const str = fs.readFileSync('./index.html')
ctx.set('content-type', 'text/html')
ctx.body = str
})
router.get('*', function(ctx, next){
ctx.body = '404'
})
app.use(router.routes())
.use(router.allowedMethods());
wsRouter.get('/ws', function(ctx, next){
const id = ctx.request.query.id
const uuid = uuidv4()
const msg = id ? 'welcome!' : '请设置id参数。如localhost:3000/show?id=abc123'
ctx.websocket.send(msg);
if (id) {
addConnection(id, uuid, ctx.websocket)
ctx.websocket.on('close', function () {
removeConnection(id, uuid)
})
}
})
websockify(app);
app.ws
.use(wsRouter.routes())
.use(wsRouter.allowedMethods())
app.listen(3000);