-
Notifications
You must be signed in to change notification settings - Fork 3
/
long_polling.js
64 lines (48 loc) · 1.39 KB
/
long_polling.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
const express = require('express');
const app = express();
class CodeGenerator{
constructor(){
this.code = ('' + Math.random()).slice(-8);
this.previousCode = this.code;
let self = this;
//每隔10秒刷新一次
function generateCode(){
return new Promise((resolve) => {
setTimeout(() => {
let code = ('' + Math.random()).slice(-8);
resolve(code);
self.previousCode = self.code;
setTimeout(() => self.previousCode = self.code, 2000);
self.code = code;
self.promise = generateCode();
}, 10000);
});
}
this.promise = generateCode().catch(()=>{});
}
generate(){
return this.promise;
}
check(code){
return this.code === code || this.previousCode === code;
}
}
let codeGenerator = new CodeGenerator();
app.get('/qrcode/:previous', async function (req, res) {
res.setHeader('Access-Control-Allow-Origin', 'http://c.h5jun.com');
let clientPrevious = req.params.previous;
let code = codeGenerator.code;
if(clientPrevious === code){ //上一次获取的还没有过期
code = await codeGenerator.generate();
}
//新的code
res.send({code});
});
app.get('/check/:code', function(req, res) {
let checkCode = req.params.code;
let msg = '验证不通过';
if(codeGenerator.check(checkCode))
msg = '验证通过';
res.send(msg);
});
app.listen(9999);