Guest User

Untitled

a guest
Nov 24th, 2018
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.02 KB | None | 0 0
  1. /**
  2. * Module dependencies.
  3. */
  4. var io = require('socket.io')
  5. , sio, sio_client_on
  6. , express = require('express')
  7. , MemoryStore = express.session.MemoryStore
  8. , routes = require('./routes')
  9. , sessionStore = new MemoryStore();
  10.  
  11.  
  12. var app = module.exports = express.createServer();
  13.  
  14. // Configuration
  15.  
  16. app.configure(function(){
  17. app.set('views', __dirname + '/views');
  18. app.set('view engine', 'ejs');
  19. app.use(express.cookieParser());
  20. app.use(express.session({store: sessionStore , secret: 'secret' , key: 'express.sid'}));
  21. app.use(express.bodyParser());
  22. app.use(express.methodOverride());
  23. app.use(app.router);
  24. app.use(express.static(__dirname + '/public'));
  25. });
  26.  
  27. app.configure('development', function(){
  28. app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
  29. });
  30.  
  31. app.configure('production', function(){
  32. app.use(express.errorHandler());
  33. });
  34.  
  35.  
  36. // User validation
  37. var auth = express.basicAuth(function(user, pass) {
  38. return (user=="mypass"&&pass=="mypass") ? true : false;
  39. },'Secret Area');
  40.  
  41. // Routes
  42.  
  43. app.get('/', routes.index);
  44. app.get('/testpage',auth, routes.t);
  45.  
  46. /// general program
  47.  
  48. var mysql = require('mysql');
  49. sqldb = mysql.createClient({user: 'root', database:'data'});/// no var, to the global scope;
  50. var sql=sqldb;
  51. sqldb.query("set names utf8");
  52.  
  53.  
  54. var dataslist;
  55.  
  56.  
  57. // excaption handling
  58.  
  59. process.on('uncaughtException', function (err) {
  60. console.log('Caught exception: ' + err.stack);
  61. });
  62.  
  63. // socket io set up
  64.  
  65. app.listen(3002); console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
  66. sio = io.listen(app);
  67. sio.set('log level', 1);
  68. sio.secret_keyword='server'
  69.  
  70. var parseCookie = require('connect').utils.parseCookie;
  71.  
  72. sio.set('authorization', function (handshake_data, accept) {
  73. var data = handshake_data;
  74. if (data.headers.cookie) {
  75. data.cookie = parseCookie(data.headers.cookie);
  76. data.sessionID = data.cookie['express.sid'];
  77. // (literally) get the session data from the session store
  78. sessionStore.load(data.sessionID, function (err, session) {
  79. if (err) {
  80. // if we cannot grab a session, turn down the connection
  81. accept(err.message, false);
  82. } else {
  83. data.session = session;
  84. //console.log('data.session',data.session)
  85. accept(null, true);
  86. }
  87. });
  88. } else {
  89. // Check to see if the conection is made from the server
  90. // ~ auth with token
  91. if (data.query.secret_keyword &&
  92. (data.query.secret_keyword === sio.secret_keyword))
  93. {
  94. return accept(null, true);
  95. }
  96. return accept('No cookie transmitted.', false);
  97. }
  98. });
  99.  
  100. sio.sockets.on('connection', function (socket) {
  101. var hs = socket.handshake;
  102. //console.log('connection',socket.handshake);
  103. console.log('A socket with sessionID ' + hs.sessionID + ' connected!');
  104. // setup an inteval that will keep our session fresh
  105. var intervalID = setInterval(function () {
  106. // reload the session (just in case something changed,
  107. // we don't want to override anything, but the age)
  108. // reloading will also ensure we keep an up2date copy
  109. // of the session with our connection.
  110. if(hs&&hs.session)hs.session.reload( function () {
  111. // "touch" it (resetting maxAge and lastAccess)
  112. // and save it back again.
  113. hs.session.touch().save();
  114. });
  115. }, 60 * 1000);
  116. socket.on('disconnect', function () {
  117. console.log('A socket with sessionID ' + hs.sessionID + ' disconnected!');
  118. // clear the socket interval to stop refreshing the session
  119. clearInterval(intervalID);
  120. });
  121. socket.join(socket.handshake.sessionID);
  122. setup_socket_io(socket);
  123. });
  124.  
  125. function setup_socket_io(client)
  126. {
  127. Object.keys(sio_client_on)
  128. .forEach(function(eventName){
  129. var f=sio_client_on[eventName];
  130. client.on(eventName,function(){f.apply(client,arguments)});});
  131. }
  132.  
  133. //// socket io events
  134.  
  135. sio_client_on=
  136. {
  137. 'message': function (message) {
  138. console.log("message",message)
  139. //if (message.event == 'homepage loaded') {
  140. //client.broadcast(...);
  141. //}
  142. },
  143. 'test': function (d) {
  144. console.log("test",d)
  145. //if (message.event == 'homepage loaded') {
  146. // this.broadcast('gotticks');
  147. //}
  148. // sio.sockets.emit('eval','alert("Man, good to see you back!1")');
  149. //sio.sockets.in(req.sessionID).send('Man, good to see you back!');
  150. },
  151. 'dataslist': function (d) {
  152. this.emit('dataslist',dataslist);
  153. console.log("dataslist",dataslist.length,d?d:'')
  154. //if (message.event == 'homepage loaded') {
  155. // this.broadcast('gotticks');
  156. //}
  157. // sio.sockets.emit('eval','alert("Man, good to see you back!1")');
  158. //sio.sockets.in(req.sessionID).send('Man, good to see you back!');
  159. }
  160. 'update_something':function(d)
  161. {
  162. sqldb.query("UPDATE datas SET something="+parseFloat(d.something)+" where dataid="+sql.escape(d.dataid)+"")
  163. .on('error', function(err) {if (err) throw err;})
  164. .addListener('end', function() { setTimeout( selectdataslist,500); })
  165. }
  166. }
  167.  
  168. 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
  169. res.end('ok');
  170. sio.sockets.emit('eval','if(refreshdata)refreshdata()'); // emit to all clients
  171. });
  172.  
  173. app.get('/getdata/:fromdate/:todate/:id?', function (req, res) { // example how to use params
  174. res.send([req.params.fromdate,req.params.todate,req.params.id]); // retun json with the arguments
  175. });
  176.  
  177. app.get('/dataslist', function (req, res) {
  178. res.send(datalist); // send json data
  179. });
  180.  
  181. function selectdatalist(cb)
  182. {
  183. console.log('select dataslist called');
  184. var tdataslist=[];
  185. sqldb.query("SELECT * FROM datas where updated=1")
  186. .on('error', function(err) {if (err) throw err;})
  187. .addListener('row', function(r) { tdataslist.push(r);})
  188. .addListener('end', function() { dataslist=tdataslist;if(cb)cb(); })
  189. }
  190. setInterval(selectdataslist,120*1000);
  191. setTimeout( selectdataslist,500);
Add Comment
Please, Sign In to add comment