PageRenderTime 82ms CodeModel.GetById 40ms app.highlight 5ms RepoModel.GetById 35ms app.codeStats 0ms

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

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