Hola NodeJS, chat client using socket io

It was about time to play with NodeJS. It definitely WOW’ed me interms of performance and simplicity. Today I am going to share my experience building a chat client using NodeJS. This is one of the famous “Hello World” type application demo’ed.
If you haven’t already, you can setup node js by following the steps outlined on their website.

Creating simple http server
Let me demonstrate how easy it is to create a simple http server with node.
Create a js file and name it “server.js” and put the contents below:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'}); + '\n'
  res.end('Hello World\n');
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');

What we are doing above is that, we are requiring http module and listening on port 8080.
When a request comes, we are responding with the famous “Hello World” text.

To start the server simply run the following command:

$ node server.js

Now on your browser, navigate to “http://localhost:8080 ” , walla.. “Hello World”! (Note: you can go to any url on that port will respond back with same response, like http://localhost:8080/foo/bar will still resolve to same response.)

“npm” – Node Packaged Modules
Node comes with a really nice package manager called npm. If you are familier with package managers such as apt-get, yum, brew etc, you will find it right at home.

To install any package just type “npm install ”
For instance, to install “socket.io” module we would run the following:

  $   npm install socket.io

This will create a directory named “node_modules” and the requested module is pulled in there.
Alright, now we have enough arsenal to get started with the our topic.

Let’s Chat, shall we?
To start, lets create a directory so we can put our resources in there. Lets name it “NodeChat”.
Inside the directory let’s create a file with name, ‘server.js’. We will edit this in a bit.
On the command line run the following commands to install modules required by our program.

$ npm install socket.io
$ npm install node-static

socket.io is used for the websocket communication we will have between server and the browser.
node-static will let us serve static files via nodejs.

Now we have that lets hack-away our server.js.
To start lets say that we will just “post message” to the server and server will broadcast it to all the clients.

To start, let’s build a web server component. As we did in above example we will do the following:

var app = require('http').createServer(handler),
io = require ('socket.io').listen(app),
static = require('node-static');

Here we are building a web server. The “handler” is a function I will show in a bit. The “socket.io” will listen on the http server we just created.

Now, we can add the following:

// Make all the files in the current directory accessible
var fileServer = new static.Server('./');

app.listen(8080);

That piece is self explanatory. Now to the important piece, we will add the handler and the socket.io stuff.
Below is the complete contents of the file when we will be done.

//Node.js Chat client Server

var app = require('http').createServer(handler),
io = require ('socket.io').listen(app),
static = require('node-static');

// Make all the files in the current directory accessible
var fileServer = new static.Server('./');

app.listen(8080);

function handler(request, response) {
	request.addListener('end', function () {
		fileServer.serve(request, response);
	});
}

io.sockets.on('connection', function(socket) {
	socket.on('postMessage', function(data){
		socket.broadcast.emit('message', data);
		socket.emit('message', data);
	});
});

Here, the function handler is simply delegating to serve the static content requested.
Important part is the io.sockets piece. When a client fires the ‘postMessage’ event, we will run the closure attached to the event on the server. In this case, we simply trigger the ‘message’ event along with the data on all the active clients except for the socket that trigged it. To echo the message back, we trigger the ‘message’ event on the socket itself with the data.

Now we have the backend ready lets work on the Front-end.

Create “index.html” and paste the following html code.

<!DOCTYPE HTML>
<html>
<head>
	<title>Live Chat Powered by Node.js</title>
	<script src="/socket.io/socket.io.js"></script>
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
	<script>
	$(document).ready(function () {
		var socket = io.connect('http://localhost:8080');

    	//Bind the "send" button to do a post
    	$("#send-btn").bind('click', function() {
    		socket.emit('postMessage', {text: $("#message-box").val()});
    		$("#message-box").val('');
    	});

    	//on socket message from server
    	socket.on('message', function(data) {
    		$("#message-board").append( data.text + "<br/>");
    	});

    });
	</script>
	<style>
	#message-board {
		width: 500px;
		height: 400px;
	}
	</style>
</head>
<body>
	<div id="content">
		<div id="message-board"></div>
		<input id="message-box" type="text" size="100" placeholder="Type a message..."/>
		<button id="send-btn">send</button>
	</div>
</body>
</html>

Here we have simple page with one text box and one button.
Using jQuery, when the page is loaded, we create a socket connection to the server.
When ‘click’ event is fired, we fire the ‘postMessage’ event with the text value from the ‘message-box’ input. and we clear the box for user to type new message.
When the server fires the ‘message’ event on our local client script will simply append the text on the “message-board” div.
Here you go we have a very simple Chat client.

I have added some flare to it, you can find the code at https://github.com/manijshrestha/NodeChat

Building app with responsive design using jQuery mobile and CSS3 (Media Query)

Having built few mobile apps with HTML5 and CSS, it allowed to build apps quickly with simple text editor using HTML and JS. Recently it has been very popular. There are many really good frameworks such as Sencha, Jo, The-M-Project , KendoUI just to name a few. JQuery Mobile is probably one of the simplest one to get started with.

One of the challenges these days is building an app that works on both phone and tablet¬† (able to utilize larger screen sizes). Today, I am going to quickly demonstrate building of a simple mobile app with “Responsive” mobile design that would work on both mobile phone as well as tablet. Just to show the end result,¬† here is what we will have at the end:

Wireframe: To get started let’s starts with code below. You can read more about it on jQuery Mobile website.

<!DOCTYPE html> 
<html> 
<head> 
	<title>Page Title</title> 
	
	<meta name="viewport" content="width=device-width, initial-scale=1"> 

	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
	<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
	<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head> 
<body> 

<div data-role="page">

	<div data-role="header">
		<h1>Cool App</h1>
	</div><!-- /header -->

	<div data-role="content">	
		<p>Some Cool Stuff</p>		
	</div><!-- /content -->
</div><!-- /page -->

</body>
</html>

If you crate index.html with above code you will have a mobile app using jQuery mobile:).

Adding Menu: Lets add the menu and some content. To do this, lets create two divs,
“menu-pane” and “content-pane”. These would be the direct child under “content” div.

<div data-role="content">
<div id="menu-pane">
<ul data-role="listview">
	<li><a id="menu-item-1" href="#">Menu Item 1</a></li>
	<li><a id="menu-item-2" href="#">Menu Item 2</a></li>
</ul>
</div>
<div id="content-pane">
 Some Cool Stuff</div>
</div>
<!-- /content -->

You should see a page like below:

Behavior on buttons: Now, Lets add a behavior when if we click on any menu item it will simply pop up ‘Not Yet Implemented’.
you can do so by adding following jQuery block in side the head tag.

<script type="text/javascript">
		$(document).ready(function() {

			//Just an alert to show its not implatemented..
			$("#menu-item-1, #menu-item-2").click( function () {alert("Not yet Implemented.")});

		}); // end of document Ready

</script>

CSS for menu: Let’s add a tiny little CSS so that menu and content page looks better on tablet.

<style>
	  #menu-pane {
		  width: 30%;
		  float: left;
		  }

	  #content-pane {
			width: 70%;
			height: 100%;
			float: left;
			text-align: center;
		}
</style>

At this time you should have a nice looking interface good for tablet. Similar to page below:

This wouldn’t look so nice on a mobile phone, and we are going to fix that next.
Idea here is that we are going to add a menu button on top right which will expose the menu for user on mobile phone and n tablet menu just appears on the left side.

Options Button: So, lets add a button in the HTML that will on click open a pop up with menu items. To do this, we will add a button and a empty popup div in which we will populate dynamically. Add the following HTML inside the header div.

<a id="options-btn" class="ui-btn-right" href="#popupPanel" data-icon="gear" data-rel="popup">Options</a>
<!-- Popup Menu Content -->
<div data-role="popup" id="popupPanel"><!--Empty for now--></div>

Populating Popup Menu: Now since we have an empty div for popup, lets populate that with the menu we have on the screen. Based on your implementation, you may choose to do it differently.

Add the following javascript in the document.ready function. This will just copy the HTML from #menu-pane in to the #popupPanel

$("#popupPanel").html($("#menu-pane").html());

You can see the ui would look something like below:

Making it “Responsive” with Media Query: Now finally we want to make it “Responsive” by using media query. What we would want to do is that,
when its on a tablet, we want to take off the “Options” button. And, when we are on a mobile phone we want to remove the menu from left and show the “Options” button.
Let’s do that by adding media query css.

  /* Hide the menu-pane when on mobile */
		@media screen and (max-width: 480px) {
	      #menu-pane{
			display: none;
		  }

		}

Also lets update the existing css we had before and wrap it for tablet view.

/* Hide Options button on tablet */
		@media screen and (min-width: 481px) {
		  #menu-pane {
			  width: 30%;
			  float: left;
			  }

	      #content-pane {
				width: 70%;
				height: 100%;
				float: left;
				text-align: center;
			}

			#options-btn {
					display: none;
			}
		}

At this time we have have a working app that works on both tablet and mobile! On the browser, you can change the browser and see it in action :).

Complete source code of this could be found in github at: https://github.com/manijshrestha/jQueryMobileResponsiveDemo

Final output: The final HTML would look like one below:

<!DOCTYPE html> 
<html> 
<head> 
	<title>Cool App</title> 
	
	<meta name="viewport" content="width=device-width, initial-scale=1"> 

	<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
	<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
	<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
	
	<script type="text/javascript">
		$(document).ready(function() {
			$("#popupPanel").html($("#menu-pane").html());	
			//Just an alert to show its not implatemented..
			$("#menu-item-1, #menu-item-2").click( function () {alert("Not yet Implemented.")});
		
		}); // end of document Ready
	</script>
	
	<style>
		
	  /* Hide the menu-pane when on mobile */	 
		@media screen and (max-width: 480px) {
	      #menu-pane{
			display: none;
		  }

		}
		
	  /* Hide Options button on tablet */
		@media screen and (min-width: 481px) {
		  #menu-pane {
			  width: 30%;
			  float: left;
			  }
	      
	      #content-pane {
				width: 70%;
				height: 100%;
				float: left;
				text-align: center;
			}
			
			#options-btn {
					display: none;
			}
		}
		
	</style>
	
</head> 
<body> 

<div data-role="page">

	<div data-role="header">
		<h1>Cool App</h1>
		<a id="options-btn" href="#popupPanel" data-icon="gear" data-rel="popup" class="ui-btn-right">Options</a>		
		<!-- Popup Menu Content -->
		<div data-role="popup" id="popupPanel" >
			<!--Empty for now-->
		</div>
	</div><!-- /header -->

	<div data-role="content">
		<div id="menu-pane">
		   <ul data-role="listview">
				<li><a id="menu-item-1" href="#">Menu Item 1</a></li>
				<li><a id="menu-item-2" href="#">Menu Item 2</a></li>
		   </ul>
		</div>
		
		<div id="content-pane">	
			<p>		Some Cool Stuff		</p>		
		</div>
		
	</div><!-- /content -->
</div><!-- /page -->

</body>
</html>

Hope you enjoyed this post. Thank you,

Waking up to CoffeeScript

Just clicking around on github today ran into some files with “.coffee” extension. First I thought someone wanted to be funny with the ‘name’ as they might be drinking way too much coffee while sitting in front of a computer, coding. Checking the contents of the file things looked interesting.
I turned to our best friend ‘google’ and found out about coffee script!
I am not sure if I will be using it in any of my project any time soon, but I thought I should just start with a little ‘Hello World’.

You can find more info on their website, http://jashkenas.github.com/coffee-script/

Installing CoffeeScript
I am on Ubuntu, so, here are steps on how to install CoffeeScript on Ubuntu.
At the time of this writing, the latest version of coffeescript is 1.1.2.
CoffeeScript depends on “Node.js”, so we have to install Node.js first.(0.4.12 is the latest version at the time of writing)

Let’s Install the Node.js

$ wget http://nodejs.org/dist/node-v0.4.12.tar.gz
$ tar xzvf node-v0.4.12.tar.gz

At this point you should have nodejs ready to be configured.
Let’s configure it next

$ cd node-v0.4.12/
$ ./configure  --without-ssl
$ make

(Note: I had issues with ssl so I had to configured it without ssl, you may try without the flag)

Congratulations, you have successfully configured node.js!

Now, Lets Move on to CoffeeScript

Download the latest CoffeeScript and set up by following the steps below:

$ wget --no-check-certificate --trust-server-names     http://github.com/jashkenas/coffee-script/tarball/1.1.2

$ tar xzvf 1.1.2

Once you are done with above steps, you should have a directory something like, ‘jashkenas-coffee-script-1a652a9’

Lets take it for a test drive

$ cd jashkenas-coffee-script-1a652a9
$ bin/coffee --version

You should see an output similar to below:
CoffeeScript version 1.1.2

Create a file and call it “test.coffee” (in same location are you at right now)

alert 'Hello World!'

$
Let’s Compile, to compile a coffee script you simply type the following:

$ bin/coffee -c test.coffee 

You should see a file called ‘test.js’ with content

(function() {
  alert('Hello World!');
}).call(this);

We have successfully written a first “CoffeeScript” Code!
There are tons of examples on their site, we can give it a try at some point.

Reference: http://net.tutsplus.com/tutorials/javascript-ajax/rocking-out-with-coffeescript/