Last active
June 13, 2018 17:38
-
-
Save iinsta/69697450890771b3d3c38910d6471aa8 to your computer and use it in GitHub Desktop.
long poll pratice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const p = require('polka')(); | |
const debounce = require('lodash/debounce'); | |
p.get('/', (req, res) => { | |
res.end('hello world') | |
}) | |
const maxConnections = 10*10000; | |
const todos = ['hello']; | |
const users = Object.create(null); | |
p.post('/long-poll/:UserID', (req, res) => { | |
const { UserID } = req.params; | |
if (!UserID) return res.end('error'); | |
if (!users[UserID]) { | |
users[UserID] = Object.create(null); | |
res.end(JSON.stringify(todos)); | |
count++; | |
if (count >= maxConnections) { | |
checkExpiredConnection(Object.keys(users), 5000); | |
} | |
} else { | |
users[UserID].sub && users[UserID].sub('Warn The Old One has a new client, and stop pooling'); | |
users[UserID].time = +new Date(); | |
users[UserID].sub = function(todos) { | |
res.end(JSON.stringify(todos)); | |
} | |
} | |
}) | |
// delete lost connections; | |
const checkExpiredConnection = debounce(function (uks, expired, cb) { | |
uks.forEach(k => { | |
const {time, sub} = users[k]; | |
if (+new Date() - time >= expired) { // if ten seconds long,end; | |
sub && sub(''); | |
delete users[k]; | |
count--; | |
} | |
sub && sub(todo); | |
}) | |
cb && cb(); | |
}, 200); | |
// loop check | |
function loopCheckExpiredConnection() { | |
setTimeout(() => { | |
checkExpiredConnection(Object.keys(users), 10000, loopCheckExpiredConnection); | |
}, 10000) | |
} | |
// debounce process emit new todos | |
const emitNewTodo = debounce(function(todo, PrevID) { | |
Object.keys(users).forEach(k => { | |
const {sub} = users[k]; | |
let goon = null; | |
for (let i = 0; i<=todos.length; i++) { | |
if (todos[i].ID === PrevID) { | |
goon = []; | |
} | |
if (goon) { | |
goon.push(todos[i]) | |
} | |
} | |
sub && sub(goon); | |
}); | |
}, 200); | |
p.get('/new/todo/:todo', (req, res) => { | |
const {todo, PrevID} = req.params; | |
todos.push(todo); | |
res.end('ok'); | |
emitNewTodo(todo, PrevID); | |
}) | |
p.get('/cache', (req, res) => { | |
res.end(JSON.stringify({todos: todos, users: users,})) | |
}) | |
p.listen(3000).then(() => { | |
loopCheckExpiredConnection(); | |
console.log('> Running on localhost:3000'); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment