Advertisement
Guest User

Untitled

a guest
Apr 3rd, 2016
424
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.19 KB | None | 0 0
  1. var app = require('http').createServer(handler),
  2. io = require('socket.io').listen(app),
  3. fs = require('fs'),
  4. mysql = require('mysql'),
  5. connectionsArray = [],
  6. connection = mysql.createConnection({
  7. host: 'localhost',
  8. user: 'root',
  9. password: '',
  10. database: 'livedbtest',
  11. port: 3306
  12. }),
  13. POLLING_INTERVAL = 1000,
  14. pollingTimer;
  15.  
  16. // If there is an error connecting to the database
  17. connection.connect(function(err) {
  18. // connected! (unless `err` is set)
  19. if (err) {
  20. console.log(err);
  21. }
  22. });
  23.  
  24. // creating the server ( localhost:8000 )
  25. app.listen(8000);
  26.  
  27. // on server started we can load our client.html page
  28. function handler(req, res) {
  29. fs.readFile(__dirname + '/client.html', function(err, data) {
  30. if (err) {
  31. console.log(err);
  32. res.writeHead(500);
  33. return res.end('Error loading client.html');
  34. }
  35. res.writeHead(200);
  36. res.end(data);
  37. });
  38. }
  39.  
  40. /*
  41. *
  42. * HERE IT IS THE COOL PART
  43. * This function loops on itself since there are sockets connected to the page
  44. * sending the result of the database query after a constant interval
  45. *
  46. */
  47.  
  48. var pollingLoop = function() {
  49.  
  50. // Doing the database query
  51. var query = connection.query('SELECT * FROM users'),
  52. users = []; // this array will contain the result of our db query
  53.  
  54. // setting the query listeners
  55. query
  56. .on('error', function(err) {
  57. // Handle error, and 'end' event will be emitted after this as well
  58. console.log(err);
  59. updateSockets(err);
  60. })
  61. .on('result', function(user) {
  62. // it fills our array looping on each user row inside the db
  63. users.push(user);
  64. })
  65. .on('end', function() {
  66. // loop on itself only if there are sockets still connected
  67. if (connectionsArray.length) {
  68.  
  69. pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);
  70.  
  71. updateSockets({
  72. users: users
  73. });
  74. } else {
  75.  
  76. console.log('The server timer was stopped because there are no more socket connections on the app')
  77.  
  78. }
  79. });
  80. };
  81.  
  82.  
  83. // creating a new websocket to keep the content updated without any AJAX request
  84. io.sockets.on('connection', function(socket) {
  85.  
  86. console.log('Number of connections:' + connectionsArray.length);
  87. // starting the loop only if at least there is one user connected
  88. if (!connectionsArray.length) {
  89. pollingLoop();
  90. }
  91.  
  92. socket.on('disconnect', function() {
  93. var socketIndex = connectionsArray.indexOf(socket);
  94. console.log('socketID = %s got disconnected', socketIndex);
  95. if (~socketIndex) {
  96. connectionsArray.splice(socketIndex, 1);
  97. }
  98. });
  99.  
  100. console.log('A new socket is connected!');
  101. connectionsArray.push(socket);
  102.  
  103. });
  104.  
  105. var updateSockets = function(data) {
  106. // adding the time of the last update
  107. data.time = new Date();
  108. console.log('Pushing new data to the clients connected ( connections amount = %s ) - %s', connectionsArray.length , data.time);
  109. // sending new data to all the sockets connected
  110. connectionsArray.forEach(function(tmpSocket) {
  111. tmpSocket.volatile.emit('notification', data);
  112. });
  113. };
  114.  
  115. console.log('Please use your browser to navigate to http://localhost:8000');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement