Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var http = require('http'),
  2.         url = require('url'),
  3.         fs = require('fs'),
  4.         io = require('../'),
  5.         sys = require('sys'),
  6.         counter =0,
  7.         path = '',
  8.  
  9. server = http.createServer(function(req, res){
  10.     // your normal server code
  11.     path = url.parse(req.url).pathname;
  12.     switch (path){
  13.         case '/':
  14.             res.writeHead(200, {'Content-Type': 'text/html'});
  15.             res.write('<h1>Welcome. Try the <a href="/chat.html">chat</a> example.</h1>');
  16.             res.end();
  17.             break;
  18.       case '/pixel.html':
  19.         case '/json.js':
  20.         case '/report.html':
  21.             fs.readFile(__dirname + path, function(err, data){
  22.                 if (err) return send404(res);
  23.                 res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'})
  24.                 res.write(data, 'utf8');
  25.                 res.end();
  26.             });
  27.             break;
  28.            
  29.         default: send404(res);
  30.     }
  31. }),
  32.  
  33. send404 = function(res){
  34.     res.writeHead(404);
  35.     res.write('404');
  36.     res.end();
  37. };
  38.  
  39. server.listen(80);
  40.  
  41.  
  42. buffer = [];
  43. var counter = 0;
  44.  
  45. // socket.io, I choose you
  46. // simplest chat application evar
  47.  
  48. server.addListener("request", function(socket){
  49.     if (path == '/pixel.html') {
  50.         counter++;
  51.         //io.broadcast({counter});
  52.         console.log('pixel requested! request #' + counter);
  53.     }
  54.   });  
  55.  
  56.  
  57. var io = io.listen(server);
  58.  
  59. // lost to how i should use the socket.io to pass the counter at an interval of time.
  60. // say send the counter once a second to any listening clients
  61. io.on('connection', function(client){
  62.     console.log('someone connected!');
  63.     client.send({ buffer: buffer });
  64.     client.broadcast({ announcement: counter });
  65.    
  66.     client.on('message', function(message){
  67.         var msg = { message: [client.sessionId, message + ' :: ' + counter] };
  68.         buffer.push(msg);
  69.         if (buffer.length > 15) buffer.shift();
  70.         client.broadcast(msg);
  71.     });
  72.  
  73.     client.on('disconnect', function(){
  74.     });
  75. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement