Skip to content

Instantly share code, notes, and snippets.

@tnylea
Created July 1, 2012 20:05
Show Gist options
  • Save tnylea/3029418 to your computer and use it in GitHub Desktop.
Save tnylea/3029418 to your computer and use it in GitHub Desktop.
appjs file for simple chat
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(5432);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
// name and emails in the chat
var names = {};
var emails = {};
var user_count = 0;
io.sockets.on('connection', function (socket) {
add_new_user(socket);
add_new_message(socket);
remove_user(socket);
});
function add_new_user(socket){
socket.on('new_user', function(name, email){
if(name != null && email != null){
// store the name
socket.name = name;
// store the email
socket.email = email;
socket.user_index = user_count;
// add the new user to the names array
names[socket.user_index] = name;
// add the new user email to the emails array
emails[socket.user_index] = email;
// let the new user now that they've been added to the chat
socket.emit('add_message', 'New User Added', name);
// let everyone else know that the new user has joined the chat
socket.broadcast.emit('add_message', name, 'joined the chat');
// update connected users list
io.sockets.emit('update_users', names, emails);
// increment the user count
user_count += 1;
// update user_count
io.sockets.emit('update_user_count', user_count);
}
});
}
function add_new_message(socket){
socket.on('send_message', function (data) {
// when message is sent add the message
io.sockets.emit('add_message', socket.name, data);
});
}
function remove_user(socket){
socket.on('disconnect', function(){
if(socket.name != null){
// remove the name from the name list
delete names[socket.user_index];
// remove the email from the email list
delete emails[socket.user_index];
// update list of users
io.sockets.emit('update_users', names, emails);
// echo globally that this client has left
socket.broadcast.emit('add_message', socket.name, 'quit the chat');
// decrement user_count
user_count -= 1;
// update user_count
io.sockets.emit('update_user_count', user_count);
}
});
}
@ivikash
Copy link

ivikash commented Jan 15, 2013

Thank-You for this. Its really helpful.

I am trying to save the entire chat in mongoDB, can you please help me with that. I have made a revision here https://gist.github.com/4536606 but the problem is its, logging only the first msg and not everything

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment