Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Module dependencies.
- */
- var io = require('socket.io')
- , sio, sio_client_on
- , express = require('express')
- , MemoryStore = express.session.MemoryStore
- , routes = require('./routes')
- , sessionStore = new MemoryStore();
- var app = module.exports = express.createServer();
- // Configuration
- app.configure(function(){
- app.set('views', __dirname + '/views');
- app.set('view engine', 'ejs');
- app.use(express.cookieParser());
- app.use(express.session({store: sessionStore , secret: 'secret' , key: 'express.sid'}));
- app.use(express.bodyParser());
- app.use(express.methodOverride());
- app.use(app.router);
- app.use(express.static(__dirname + '/public'));
- });
- app.configure('development', function(){
- app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
- });
- app.configure('production', function(){
- app.use(express.errorHandler());
- });
- // User validation
- var auth = express.basicAuth(function(user, pass) {
- return (user=="mypass"&&pass=="mypass") ? true : false;
- },'Secret Area');
- // Routes
- app.get('/', routes.index);
- app.get('/testpage',auth, routes.t);
- /// general program
- var mysql = require('mysql');
- sqldb = mysql.createClient({user: 'root', database:'data'});/// no var, to the global scope;
- var sql=sqldb;
- sqldb.query("set names utf8");
- var dataslist;
- // excaption handling
- process.on('uncaughtException', function (err) {
- console.log('Caught exception: ' + err.stack);
- });
- // socket io set up
- app.listen(3002); console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
- sio = io.listen(app);
- sio.set('log level', 1);
- sio.secret_keyword='server'
- var parseCookie = require('connect').utils.parseCookie;
- sio.set('authorization', function (handshake_data, accept) {
- var data = handshake_data;
- if (data.headers.cookie) {
- data.cookie = parseCookie(data.headers.cookie);
- data.sessionID = data.cookie['express.sid'];
- // (literally) get the session data from the session store
- sessionStore.load(data.sessionID, function (err, session) {
- if (err) {
- // if we cannot grab a session, turn down the connection
- accept(err.message, false);
- } else {
- data.session = session;
- //console.log('data.session',data.session)
- accept(null, true);
- }
- });
- } else {
- // Check to see if the conection is made from the server
- // ~ auth with token
- if (data.query.secret_keyword &&
- (data.query.secret_keyword === sio.secret_keyword))
- {
- return accept(null, true);
- }
- return accept('No cookie transmitted.', false);
- }
- });
- sio.sockets.on('connection', function (socket) {
- var hs = socket.handshake;
- //console.log('connection',socket.handshake);
- console.log('A socket with sessionID ' + hs.sessionID + ' connected!');
- // setup an inteval that will keep our session fresh
- var intervalID = setInterval(function () {
- // reload the session (just in case something changed,
- // we don't want to override anything, but the age)
- // reloading will also ensure we keep an up2date copy
- // of the session with our connection.
- if(hs&&hs.session)hs.session.reload( function () {
- // "touch" it (resetting maxAge and lastAccess)
- // and save it back again.
- hs.session.touch().save();
- });
- }, 60 * 1000);
- socket.on('disconnect', function () {
- console.log('A socket with sessionID ' + hs.sessionID + ' disconnected!');
- // clear the socket interval to stop refreshing the session
- clearInterval(intervalID);
- });
- socket.join(socket.handshake.sessionID);
- setup_socket_io(socket);
- });
- function setup_socket_io(client)
- {
- Object.keys(sio_client_on)
- .forEach(function(eventName){
- var f=sio_client_on[eventName];
- client.on(eventName,function(){f.apply(client,arguments)});});
- }
- //// socket io events
- sio_client_on=
- {
- 'message': function (message) {
- console.log("message",message)
- //if (message.event == 'homepage loaded') {
- //client.broadcast(...);
- //}
- },
- 'test': function (d) {
- console.log("test",d)
- //if (message.event == 'homepage loaded') {
- // this.broadcast('gotticks');
- //}
- // sio.sockets.emit('eval','alert("Man, good to see you back!1")');
- //sio.sockets.in(req.sessionID).send('Man, good to see you back!');
- },
- 'dataslist': function (d) {
- this.emit('dataslist',dataslist);
- console.log("dataslist",dataslist.length,d?d:'')
- //if (message.event == 'homepage loaded') {
- // this.broadcast('gotticks');
- //}
- // sio.sockets.emit('eval','alert("Man, good to see you back!1")');
- //sio.sockets.in(req.sessionID).send('Man, good to see you back!');
- }
- 'update_something':function(d)
- {
- sqldb.query("UPDATE datas SET something="+parseFloat(d.something)+" where dataid="+sql.escape(d.dataid)+"")
- .on('error', function(err) {if (err) throw err;})
- .addListener('end', function() { setTimeout( selectdataslist,500); })
- }
- }
- app.get('/refresh', function (req, res) { // if this url called by some other server, all socket io clients of this app start to refresh data, i use it to update my window when the database is updated
- res.end('ok');
- sio.sockets.emit('eval','if(refreshdata)refreshdata()'); // emit to all clients
- });
- app.get('/getdata/:fromdate/:todate/:id?', function (req, res) { // example how to use params
- res.send([req.params.fromdate,req.params.todate,req.params.id]); // retun json with the arguments
- });
- app.get('/dataslist', function (req, res) {
- res.send(datalist); // send json data
- });
- function selectdatalist(cb)
- {
- console.log('select dataslist called');
- var tdataslist=[];
- sqldb.query("SELECT * FROM datas where updated=1")
- .on('error', function(err) {if (err) throw err;})
- .addListener('row', function(r) { tdataslist.push(r);})
- .addListener('end', function() { dataslist=tdataslist;if(cb)cb(); })
- }
- setInterval(selectdataslist,120*1000);
- setTimeout( selectdataslist,500);
Add Comment
Please, Sign In to add comment