PageRenderTime 54ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/js/lib/Socket.IO-node/example/server.js

http://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs
JavaScript | 63 lines | 47 code | 10 blank | 6 comment | 4 complexity | 538283d0a938296c2ab85327e3f79dd3 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, MPL-2.0-no-copyleft-exception, BSD-3-Clause
  1. /**
  2. * Important note: this application is not suitable for benchmarks!
  3. */
  4. var http = require('http')
  5. , url = require('url')
  6. , fs = require('fs')
  7. , io = require('../')
  8. , sys = require(process.binding('natives').util ? 'util' : 'sys')
  9. , server;
  10. server = http.createServer(function(req, res){
  11. // your normal server code
  12. var path = url.parse(req.url).pathname;
  13. switch (path){
  14. case '/':
  15. res.writeHead(200, {'Content-Type': 'text/html'});
  16. res.write('<h1>Welcome. Try the <a href="/chat.html">chat</a> example.</h1>');
  17. res.end();
  18. break;
  19. case '/json.js':
  20. case '/chat.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. default: send404(res);
  29. }
  30. }),
  31. send404 = function(res){
  32. res.writeHead(404);
  33. res.write('404');
  34. res.end();
  35. };
  36. server.listen(8080);
  37. // socket.io, I choose you
  38. // simplest chat application evar
  39. var io = io.listen(server)
  40. , buffer = [];
  41. io.on('connection', function(client){
  42. client.send({ buffer: buffer });
  43. client.broadcast({ announcement: client.sessionId + ' connected' });
  44. client.on('message', function(message){
  45. var msg = { message: [client.sessionId, message] };
  46. buffer.push(msg);
  47. if (buffer.length > 15) buffer.shift();
  48. client.broadcast(msg);
  49. });
  50. client.on('disconnect', function(){
  51. client.broadcast({ announcement: client.sessionId + ' disconnected' });
  52. });
  53. });