var express = require('express'), http = require('http'), io = require('socket.io'), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), mongojs = require('mongojs'); var app = express(); app.use(express.static('./public')); var mongoUri = "mongodb://localhost:27017/visualizer"; var db = mongojs( mongoUri ); var honeyCombs = db.collection('honeyCombs'); // honeyCombs.insert({dio: "cane", type: "flyingPig"}); //Specifying the public folder of the server to make the html accesible using the static middleware app.use(cookieParser()); var jsonParser = bodyParser.json() // create application/x-www-form-urlencoded parser var urlencodedParser = bodyParser.urlencoded({ extended: false }) // POST /login gets urlencoded bodies function findSocketByCookie(cookie) { for(var i in io.sockets.connected) { var socket = io.sockets.connected[i]; if(socket.handshake.headers.cookie.indexOf(cookie) !== -1){ return socket; } } } app.post('/show', urlencodedParser, function (req, res) { res.sendStatus(200); console.log("Sending json to live interfaces..."); // console.dir(io.sockets.connected); for(var i in io.sockets.connected) { var socket = io.sockets.connected[i]; socket.emit("jsonHoneycomb", req.body.honeyComb); saveQuery(req.body.honeyComb); } // var socket = findSocketByCookie(req.cookies.myUniqueCookie); }); var server = http.createServer(app).listen(8080); console.log("Listening on port 8080"); console.log("Send jsons to /show please."); //Server listens on the port 8124 var io = io.listen(server); /*initializing the websockets communication , server instance has to be sent as the argument */ io.sockets.on('connection', function(socket){ console.log("New Client Connected."); socket.on('disconnect', function () { console.log("Client disconnected.") }); socket.on('ackMessage', function(msg){ if(msg == "true"){ console.log('Message received.'); } }); socket.on('liveMessage', function(msg){ if(msg == "true"){ console.log('Live interface connected.'); } }); socket.on('jsonToParse', function(msg){ console.log('Json received.'); saveQuery(msg); // socket.emit("jsonHoneycomb", msg); }); }); function saveQuery(query){ var d = new Date(); d = ("00" + (d.getMonth() + 1)).slice(-2) + "/" + ("00" + d.getDate()).slice(-2) + "/" + d.getFullYear() + " " + ("00" + d.getHours()).slice(-2) + ":" + ("00" + d.getMinutes()).slice(-2) + ":" + ("00" + d.getSeconds()).slice(-2) ; console.log("Saving query in db..."); honeyCombs.insert({ honeyComb: query, dateStamp: d }); }