Skip to content

Instantly share code, notes, and snippets.

@PedroGutierrezStratio
Last active April 3, 2022 15:41
Show Gist options
  • Save PedroGutierrezStratio/5955bb97afb89f4c00ce to your computer and use it in GitHub Desktop.
Save PedroGutierrezStratio/5955bb97afb89f4c00ce to your computer and use it in GitHub Desktop.
Node.js (WebSocket with MongoDB updates)
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;
});
}
}
@hakkikonu
Copy link

you're requesting to db on every socket request. what is the difference from classic xhr request?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment