Created
November 28, 2017 01:39
-
-
Save etyp/576c2bfa952dfa30813c49a702e11127 to your computer and use it in GitHub Desktop.
This file contains 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
var app = require('express')(); | |
var http = require('http').Server(app); | |
var io = require('socket.io')(http); | |
app.get('/', function(req, res){ | |
res.sendFile(__dirname + '/index.html'); | |
}); | |
const EVENT_LOOP_TIME = 1000; | |
const connectedUsers = {}; // Structure is { userId: socket } | |
io.on('connection', function(socket){ | |
console.log('a user connected'); | |
socket.on('disconnect', function() { | |
// Clean up after user | |
}); | |
socket.on('initiateUser', function(userId) { | |
// Custom event to "set up user" (keep them in memory so we can update them on our interval) | |
if (!connectedUsers[userId]) { | |
connectedUsers.[userId] = socket; | |
} | |
}); | |
}); | |
setInterval(() => { | |
// 1. Query active games in db that our users are a part of | |
const connectedUserIds = Object.keys(connectedUsers); | |
const games = db.games.find({ members: { $in: connectedUserIds } }).toArray(); | |
// For each game, run your logic | |
games.forEach((game) => { | |
// Logic here | |
// Then if a user needs an update, emit an event to them on their socket | |
if (needsUpdate) { | |
connectedUserIds.forEach((userId) => { | |
const socket = connectedUsers[userId]; | |
socket.emit('pleaseRePoll', game._id); | |
}); | |
} | |
}); | |
}, EVENT_LOOP_TIME); | |
http.listen(3000, function(){ | |
console.log('listening on *:3000'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment