daily pastebin goal
3%
SHARE
TWEET

Untitled

a guest Jun 14th, 2018 43 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.         io = require('socket.io'),
  6.         sys = require('sys'),
  7.        
  8. server = http.createServer(function(req, res){
  9.     // your normal server code
  10.     var path = url.parse(req.url).pathname;
  11.     switch (path){
  12.         case '/':
  13.             res.writeHead(200, {'Content-Type': 'text/html'});
  14.             res.write('<h1>Welcome. Try the <a href="/chat.html">chat</a> example.</h1>');
  15.             res.end();
  16.             break;
  17.            
  18.         case '/json.js':
  19.         case '/chat.html':
  20.             fs.readFile(__dirname + path, function(err, data){
  21.                 if (err) return send404(res);
  22.                 res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'})
  23.                 res.write(data, 'utf8');
  24.                 res.end();
  25.             });
  26.             break;
  27.            
  28.         default: send404(res);
  29.     }
  30. }),
  31.  
  32. send404 = function(res){
  33.     res.writeHead(404);
  34.     res.write('404');
  35.     res.end();
  36. };
  37.  
  38. server.listen(8080);
  39.        
  40. // socket.io, I choose you
  41. // simplest chat application evar
  42. var io = io.listen(server),
  43.         buffer = [];
  44.        
  45. io.on('connection', function(client){
  46.     client.send({ buffer: buffer });
  47.     client.broadcast({ announcement: client.sessionId + ' connected' });
  48.  
  49.     client.on('message', function(message){
  50.         var msg = { message: [client.sessionId, message] };
  51.         buffer.push(msg);
  52.         if (buffer.length > 15) buffer.shift();
  53.         client.broadcast(msg);
  54.     });
  55.  
  56.     client.on('disconnect', function(){
  57.         client.broadcast({ announcement: client.sessionId + ' disconnected' });
  58.     });
  59. });
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top