Created
December 2, 2011 15:13
-
-
Save asciidisco/1423588 to your computer and use it in GitHub Desktop.
NodeChat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Module dependencies. | |
var express = require('express') | |
, stylus = require('stylus') | |
, nib = require('nib') | |
, sio = require('socket.io') | |
, app = null; | |
// Create application server | |
app = express.createServer(); | |
// App configuration | |
app.configure(function () { | |
app.use(stylus.middleware({ src: __dirname + '/public', compile: compile })); | |
app.use(express.static(__dirname + '/public')); | |
app.set('views', __dirname); | |
app.set('view engine', 'jade'); | |
function compile (str, path) { | |
return stylus(str) | |
.set('filename', path) | |
.use(nib()); | |
}; | |
}); | |
// Add app routes | |
app.get('/', function (req, res) { | |
res.render('index', { layout: false }); | |
}); | |
// Add app routes | |
app.get('/chat', function (req, res) { | |
res.render('index', { layout: false }); | |
}); | |
// Define the port the server will listen on | |
app.listen(8888, function () { | |
console.log('ChatSever listening on port: ' + app.address().port); | |
}); | |
// Socket.IO server (single process only) | |
var io = sio.listen(app) | |
, nicknames = {} | |
, numberofconnections = 0; | |
io.sockets.on('connection', function (socket) { | |
io.sockets.emit('usersconnected', numberofconnections); | |
socket.on('user message', function (msg) { | |
socket.broadcast.emit('user message', socket.nickname, msg); | |
}); | |
socket.on('nickname', function (nick, fn) { | |
if (nicknames[nick]) { | |
fn(true); | |
io.sockets.emit('usersconnected', numberofconnections); | |
} else { | |
fn(false); | |
nicknames[nick] = socket.nickname = nick; | |
numberofconnections++; | |
io.sockets.emit('usersconnected', numberofconnections); | |
socket.broadcast.emit('announcement', nick + ' connected'); | |
io.sockets.emit('nicknames', nicknames); | |
} | |
}); | |
socket.on('disconnect', function () { | |
if (!socket.nickname) return; | |
numberofconnections--; | |
delete nicknames[socket.nickname]; | |
socket.broadcast.emit('announcement', socket.nickname + ' disconnected'); | |
socket.broadcast.emit('usersconnected', numberofconnections); | |
socket.broadcast.emit('nicknames', nicknames); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment