Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var http = require('http'),
- router = require('choreographer').router(),
- redis = require('redis-node'),
- io = require('socket.io'),
- fs = require('fs'),
- config = require('./conf');
- http.ServerResponse.prototype.serveFile = function(file, type) {
- var res = this;
- type = type || 'text/html';
- fs.readFile('./public/' + file, function(err, data) {
- if(err) {
- res.writeHead(500);
- res.end("Couldn't serve " + file + ". Error: " + err);
- } else {
- res.writeHead(200, {
- 'Content-Type': type,
- 'Content-Length': data.length
- });
- res.end(data);
- }
- });
- };
- router.get('/', function(req, res) {
- res.serveFile('index.html');
- }).get('/style.css', function(req, res) {
- res.serveFile('style.css', 'text/css');
- }).get('/client.js', function(req, res) {
- res.serveFile('client.js', 'text/javascript');
- });
- var server = http.createServer(router);
- server.listen(config.port);
- var socket = io.listen(server);
- socket.on('connection', function(client) {
- var redis_client = redis.createClient();
- var redis_subscriber;
- var channel = null;
- var nick = null;
- client.on('message', function(data) {
- var packet = JSON.parse(data);
- switch(packet.cmd)
- {
- case 'join':
- channel = packet.channel.replace(/[^A-Za-z0-9_\-']/,'');
- nick = packet.nick;
- redis_client.incr('channels:' + channel);
- redis_client.sadd('channels', channel);
- redis_client.publish(channel, JSON.stringify({
- ev: 'join',
- from: nick,
- time: Math.round(new Date().getTime() / 1000),
- msg: packet.msg
- }));
- redis_subscriber = redis.createClient();
- redis_subscriber.subscribeTo(channel, function(channel, msg) {
- client.send(msg);
- });
- client.send(JSON.stringify({ev:'welcome'}));
- break;
- case 'part':
- doPart();
- break;
- case 'list':
- redis_client.smembers('channels', function(err, status) {
- client.send(JSON.stringify({
- ev: 'list',
- channels: status
- }));
- });
- break;
- case 'msg':
- if(channel == null)
- break;
- redis_client.publish(channel, JSON.stringify({
- ev: 'msg',
- from: nick,
- time: Math.round(new Date().getTime() / 1000),
- msg: packet.msg
- }));
- break;
- }
- });
- function doPart() {
- if(channel != null) {
- console.log(nick + " parted " + channel)
- redis_client.decr('channels:' + channel);
- redis_client.publish(channel, JSON.stringify({
- ev: 'part',
- from: nick,
- time: Math.round(new Date().getTime() / 1000)
- }));
- }
- if(redis_subscriber != null) {
- redis_subscriber.unsubscribe(channel);
- redis_subscriber.close();
- redis_subscriber = null;
- }
- }
- client.on('disconnect', function() {
- doPart();
- redis_client.close();
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement