Simplest chat example in node.js and socket io

Simplest Chat Server in Node.js implemented with socket.io

I'll directly start since you guys don't need introduction to node.js.I would like to comment on the feature exposed in this example of Nodejs and power of javascript running in both client and server side, it can use the event emitters  - event production and consumption design pattern elegantly. I'll give you some brief about socket.io Socket.io is a clean library with simple api calls to make possible socket level communication in node.js. It uses websocket feature in html5 but gracefully falls back to other techniques with older browsers. Methods of socket.io
  • socket.emit('message','the message to be transmitted'); //simple transmission
  • io.sockets.emit('message',"the message to be transmitted"); //send to all clients
  • socket.broadcast.emit('message',"this is a test"); //send to all except sender

Let's start creating a single room minimal chat

In this we have the following use - cases
  1. User when join the chat room, he is greeted.
  2. All Users are notified who enters the chat room.
  3. User can broadcast the message to the chat room.
Create a node module chat_server.js to achieve the above objectives.
var socketio = require('socket.io');
var io;
var guestNumber = 1;
var nickNames = {};
var namesUsed = [];

exports.listen = function(server) {
	io = socketio.listen(server);
	io.set('log level', 1);
	io.sockets.on('connection', function (socket) {
		guestNumber = assignGuestName(socket, guestNumber,nickNames, namesUsed);
		handleMessageBroadcasting(socket, nickNames);
		handleClientDisconnection(socket, nickNames, namesUsed);
	});
};

function handleMessageBroadcasting(socket,nickNames){
	socket.on('message',function(message){
		socket.broadcast.emit('message',{ text : nickNames[socket.id] + ':' + message.text });
	});
}

function handleClientDisconnection(socket,nickNames,namesUsed){
	socket.on('disconnect',function(){
		var nameIndex = namesUsed.indexOf(nickNames[socket.id]);
		socket.broadcast.emit('message',{
			text : namesUsed[nameIndex] + " left the chat room "
		});
		delete namesUsed[nameIndex];
		delete nickNames[socket.id];
	});
}

function assignGuestName(socket,guestNumber,nickNames,namesUsed){
	var name = "Guest " + guestNumber ;
	nickNames[socket.id] = name ;
	socket.emit('message', { text : "Welcome " + name});
	socket.broadcast.emit('message',{
		text : name + " has joined us. "
	});
	namesUsed.push(name);
	return guestNumber + 1 ;
}
A static file server which listens on port 80.
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
function send404(response) {
	response.writeHead(404, {'Content-Type': 'text/plain'});
	response.write('Error 404: resource not found.');
	response.end();
}

function sendFile(response, filePath, fileContents) {
	response.writeHead(
		200, {"content-type": mime.lookup(path.basename(filePath))}
	);
	response.end(fileContents);
}

function serveStatic(response, absPath) {
fs.exists(absPath, function(exists) {
if (exists) {
		fs.readFile(absPath, function(err, data) {
			if (err) {
				send404(response);
			} else {
				sendFile(response, absPath, data);
			}
		});
	} else {
		send404(response);
	}
});
}

var server = http.createServer(function(request, response) {
	var filePath = false;
	if (request.url == '/') {
		filePath = 'public/index.html';
	} 
	else {
		filePath = 'public' + request.url;
	}
	var absPath = './' + filePath;
	serveStatic(response, absPath);
});

server.listen(80, function() {
	console.log("Server listening on port.");
});

var chatServer = require('./lib/chat_server');
chatServer.listen(server);
Now the client code
<!doctype html>
<html lang='en'>
<head>
<title>Chat</title>
<link rel='stylesheet' href='/css/style.css'></link>
</head>
<body>
<div id='content'>
	<h1> My Chat Room</h1>
	<div id='messages'></div>
	<form id='send-form'>
		<input id='send-message' /><input id='send-button' type='submit' value='Send'/>
	</form>
</div>
<script src='/socket.io/socket.io.js' type='text/javascript'></script>
<script src='http://code.jquery.com/jquery-1.8.0.min.js' type='text/javascript'></script>
<script type='text/javascript'>
var socket = io.connect();
var Chat = function(socket){
	this.socket = socket ;
};
Chat.prototype.sendMessage = function(msg){
	this.socket.emit('message',{ text : msg });
};

$(document).ready(function(){
	var chatApp = new Chat(socket);
	socket.on('message',function(message){
		var newElement = $('<div  class="histext"></div>').text(message.text);
		$('#messages').append(newElement);
	});
	$('#send-form').submit(function(){
		var msg = $('#send-message').val() ;
		chatApp.sendMessage(msg);
		$('#messages').append($('<div class="mytext"></div>').text("Myself : " + msg));
		$('#send-message').val('');
	return false ;
	});
});	
</script>
</body>
</html>