Last active
April 3, 2022 15:41
-
-
Save PedroGutierrezStratio/5955bb97afb89f4c00ce to your computer and use it in GitHub Desktop.
Node.js (WebSocket with MongoDB updates)
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 http = require('http'); | |
var MongoClient = require('mongodb').MongoClient; | |
var server = require('websocket').server; | |
startMongoDBConnection(); | |
function startMongoDBConnection(){ | |
MongoClient.connect('mongodb://localhost:27017/sparta', function(err, db) { | |
startWebSocketServer(db); | |
}); | |
} | |
function startWebSocketServer(db){ | |
var connections = new Set(); // Storage of connections | |
var countries = {$in: ['de','es','fr']}; // Filter | |
var lastModification = 0; // Greater modified | |
var socket = new server({ | |
httpServer: http.createServer().listen(8008) | |
}); | |
console.log("WebScoket running on ws://localhost:8008"); | |
setLastModified(); | |
initInterval(); | |
socket.on('request', function(request) { | |
var connection = request.accept(null, request.origin); | |
connections.add(connection); | |
db | |
.collection('id_country_hour') | |
.find({country: countries}, {country: 1, count: 1, hour: 1, _id: 0}) | |
.toArray(function(err, docs){ | |
connection.send(JSON.stringify(docs)); | |
}); | |
connection.on('close', function() { | |
connections.delete(connection); | |
}); | |
}); | |
function initInterval(){ | |
setInterval(function(){ | |
db | |
.collection('id_country_hour') | |
.find({country: countries, modified: {$gt: lastModification}}, {country: 1, count: 1, hour: 1, _id: 0}) | |
.toArray(function(err, docs){ | |
if(docs.length > 0){ | |
connections.forEach(function(connection){ | |
connection.send(JSON.stringify(docs)); | |
}); | |
setLastModified(); | |
} | |
}); | |
}, 1000); | |
} | |
function setLastModified(){ | |
db | |
.collection('id_country_hour') | |
.find({$query:{},$orderby:{modified:-1}}, {modified:true}, {limit:1}) | |
.toArray(function(err,docs){ | |
lastModification = docs[0].modified; | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you're requesting to db on every socket request. what is the difference from classic xhr request?