PageRenderTime 56ms CodeModel.GetById 48ms app.highlight 5ms RepoModel.GetById 1ms 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
 1/**
 2 * Important note: this application is not suitable for benchmarks!
 3 */
 4
 5var http = require('http')
 6  , url = require('url')
 7  , fs = require('fs')
 8  , io = require('../')
 9  , sys = require(process.binding('natives').util ? 'util' : 'sys')
10  , server;
11    
12server = http.createServer(function(req, res){
13  // your normal server code
14  var path = url.parse(req.url).pathname;
15  switch (path){
16    case '/':
17      res.writeHead(200, {'Content-Type': 'text/html'});
18      res.write('<h1>Welcome. Try the <a href="/chat.html">chat</a> example.</h1>');
19      res.end();
20      break;
21      
22    case '/json.js':
23    case '/chat.html':
24      fs.readFile(__dirname + path, function(err, data){
25        if (err) return send404(res);
26        res.writeHead(200, {'Content-Type': path == 'json.js' ? 'text/javascript' : 'text/html'})
27        res.write(data, 'utf8');
28        res.end();
29      });
30      break;
31      
32    default: send404(res);
33  }
34}),
35
36send404 = function(res){
37  res.writeHead(404);
38  res.write('404');
39  res.end();
40};
41
42server.listen(8080);
43
44// socket.io, I choose you
45// simplest chat application evar
46var io = io.listen(server)
47  , buffer = [];
48  
49io.on('connection', function(client){
50  client.send({ buffer: buffer });
51  client.broadcast({ announcement: client.sessionId + ' connected' });
52  
53  client.on('message', function(message){
54    var msg = { message: [client.sessionId, message] };
55    buffer.push(msg);
56    if (buffer.length > 15) buffer.shift();
57    client.broadcast(msg);
58  });
59
60  client.on('disconnect', function(){
61    client.broadcast({ announcement: client.sessionId + ' disconnected' });
62  });
63});