Node.js and Socket.io

This example demonstrates the basic use of Node.js and Sockiet.io to create socket connections between client and server.

Node.js is a server-side JavaScript framework created by Ryan Dahl.  It’s based off of googles V8 JavaScript engine. Node.js provides a framework for running non-blocking server sided JavaScript and is geared for building scalable network programs. For more information on Node.js head over to their site. They have full api documents and a wiki.

Socket.io provides an asynchronous data connection between the client and server. It was created by Guillermo Rauch at LearnBoost.  Head over to their site for more information.

You will need to install node.js and the socket.io node module. You can install the module using NPM (node package manager).

Install NPM
curl http://npmjs.org/install.sh | sh

Follow it up by installing the socket.io module
npm install socket.io

The code below creates an HTTP server that listens on port 80 and responds with statistics on the current number of socket connections. The code also listens and accepts socket connections. It logs the connection and disconnect of the clients by incrementing client count in the connection function and decrements client count in the disconnect function.

Create a new file with js extension and add the code below. Replace the <127.0.0.1> with an IP if needed.  Run the code using the command node <filename>.js

To connect a client to the server add the html code at the bottom of the post to a file with an html extension and open it with a browser. Notice the connect and disconnect functions getting fired while you open and close the file using a browser.

//server that uses sockiet.io
var http = require('http');
var io = require('socket.io');
//setup a count variable to keep track of stuff
count = 0;
server=http.createServer(function (req, res){
     if (req.url == '/'){
          countit();
     }

     res.writeHead(200, {'Content-Type':'text/plain'});
     res.end('node.js....is running!\n'+'There are '+clientCount+' client(s) connected\nThis server has handled '+count+' requests');

     function countit (){
          count=count+1;
          console.log("Connection...increment count "+count);
          console.log("http version: "+req.httpVersion);
     }
});

server.listen(80,"127.0.0.1");
clientCount=0;

var socket=io.listen(server);
socket.on('connection',function(client){
     clientCount++;
     console.log("client is here "+clientCount);

     client.on('message',function(){
          console.log("client message");
          client.send("message");
          console.log("sent message");
     })

     client.on('disconnect',function(){
          clientCount--;
          console.log("client disconnected "+clientCount);
     })
});

console.log("running server");

HTML code

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>This is a test page</title>
<head>

<script src="http://127.0.0.1/socket.io/socket.io.js"></script>
<body>
  <script>
     var socket = new io.Socket('127.0.0.1');
     socket.connect();
     console.log('socket connected');
     socket.on('connect', function(){});
     socket.on('message', function(data){
     document.writeln('message recived: '+data);});
     socket.on('disconnect', function(){});
  </script>
Connecting to Node server!
</body>

TWiT Play Android App Update

Download version 1.0.7 in the Android Market for free. 1.0.7  update adds a sleep timer.

I am currently working on an update to add IRC functionality. Please stay tuned….

Drop me a line with feedback, comments, and requests for future versions.

Thanks

- Jamie

Smart Objects…an IP World

Give every object an IP and let it communicate with its surroundings and let its surroundings communicate with it!

This is getting to be a pretty cool age to be living in. Communication between our computers, smart phones and the internet…. lets just stuff IPs into everything we can think of ….. Technology is becoming so cheap that we can place chips into anything, making ordinary everyday objects smarter. Think about the endless possibilities…

Just to give you a taste….semiconductor company NXP based out of the Netherlands has created a series of computer chips named GreenChip.  This technology enables new GreenChip smart lighting products by including wireless IP connectivity within LED light bulbs. . The light bulbs act as individual wireless nodes and combine to create a wireless mesh network using IEEE 802.15.4. The light bulbs can then be controlled from your smart phone or computer. You can scale up or down your home lighting infrastructure by just removing or adding light bulbs….no wiring required except for power ofcourse.

Head over to NXP site for more information.

Follow Techploy on Twitter

TechployFollow Techploy on twitter! Get a tweet whenever a post gets published.

Google Data Protocol: Partial Response

A bit of old news…..but I thought it was cool … so I will bring it up … Google’s partial response! It was announced back in March of 2010.

Google’s partial response allows users to request partial xml feeds or entries by doing a simple HTTP GET with query parameters.   Instead of getting and parsing a whole XML document in your program you would only query for the data you need, making your application much more efficient.

Google partial response is part of the Google Data Protocols and is found in most of its API’s.

Hers is an example from the YouTube Data API

Here is a full upload feed from Associated Press

http://gdata.youtube.com/feeds/api/users/AssociatedPress/uploads

Lets say you wanted to you want to only get back the title and the content description of the entry feeds. You would simply just add ?fields=entry(title,content) to the URL.

Here is an URL that will give you a partial XML response of the title and content description of Associated Press uploads.

http://gdata.youtube.com/feeds/api/users/AssociatedPress/uploads?fields=entry(title,content)

There are many ways to query for data. Here is an example using operators. The URL below will return the title and content description of entries with an average rating of greater than 4.

http://gdata.youtube.com/feeds/api/users/AssociatedPress/uploads?fields=entry[gd:rating/@average>4](title,content)

hit up the Google docs API reference documentation for more syntax.

oh by the way … Google’s partial response is experimental…so be cautious :)

Amazon Appstore Test Drive

Amazon recently unleashed the Appstore and with it a feature called Test Drive. It allows you to test applications before you buy them by spawning an android virtual machine.

Amazon explains…

Clicking the “Test drive now” button launches a copy of this app on Amazon Elastic Compute Cloud (EC2), a web service that provides on-demand compute capacity in the cloud for developers. When you click on the simulated phone using your mouse, we send those inputs over the Internet to the app running on Amazon EC2 – just like your mobile device would send a finger tap to the app. Our servers then send the video and audio output from the app back to your computer. All this happens in real time, allowing you to explore the features of the app as if it were running on your mobile device.


TWiT Play Application Released

Download the new TWiT Play application for Android. It is available in the Android Market.

Listen to Leo Laporte and Friends over at TWiT. The application streams live audio directly from the TWiT studios.

At this time TWiT Play is taking the minimalist approach and will most likely add on features in the future. Stay tuned for more updates.


Android Views – Layout Parameters

Drawing views programmatically can be handy when you need to handle the orientation of dynamic content.  For example let’s say you have an XML feed and you would like to list the elements in the center of your view using a TextView and then also be able to scroll when the content doesn’t all fit in the view.

In my application I setup a ScrollView within a RelativeLayout to handle the scrolling of its children views. I then programmatically created a LinearLayout as a child view of the ScrollView. The output of the XML feed can then be added within the LinearLayout as TextViews that inherit its layout properties.

To set the layout properties of the LinearLayout view. I created a params object using FrameLayout.LayoutParams.  I then set the gravity instance variables in the layout parameters and finally called the addview method of the layout passing it the layout parameters as an argument. In the example below if my XML feed had six or less entries I would set the gravity of the view to be centered.  If there were more than six I set the gravity to the top.

//ScrollView and LinearLayout

ScrollView scrollView = (ScrollView)findViewById(R.id.scrollView1);

LinearLayout xmlLayout = new LinearLayout(this);

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

//set vertical orientation of xmlLayout view

xmlLayout.setOrientation(1)

//set gravity

if (sitesList.getTitle().size() <= 6)
  {

        params.gravity=Gravity.CENTER;

//add the LinearLayout with center gravity

        scrollView.addView(xmlLayout,params);

  }

else

  {

        params.gravity=Gravity.TOP;

//add the LienarLayout with top gravity

        scrollView.addView(xmlLayout,params);

}

//Do work and add XML entries to the LinearLayout

xmlLayout.addView(title[i]);

xmlLayout.addView(when[i]);

Note that this is not a working set of code and will not compile if copied and pasted into your program it is meant to illustrate a prof of concept.

Android Phone 7 Themed Launcher

XDA members GinoCorleone and Timo Kujala have been working on a Windows Phone 7 themed launcher for Android. For more info head over to XDA Developers to check out Launcher 7. Available now for download in the Android market.