OUR BLOG

KEEP UP TO DATE WITH OUR LATEST POSTS

« All Blog Posts

Using nodeJS for Real Time Apps

Cutting edge development article


Lately I have been working on a few projects that required some real-time communication between the browser and a centralized source of data. Now there’s a couple services out there that you can utilize but they cost money to use when you can do the same thing with just a few lines of code. There are also Microsoft resources to handle sockets too. But those typically are hard to get multi-device compatible and to really get your real-time project setup for future use and to limit the amount of maintenance. NodeJS is a great choice.
var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hellold\n');
}).listen(1337, '127.0.0.1');
console.log('Serverning at http://127.0.0.1:1337/')
Now that snippet above. Is all it takes to write a server! Simple, efficient. To get socket communications moving back and forth though takes a little bit of knowledge of how to get NodeJS up and running and installing socket.io. My current deployments are on both a windows and linux platform. The installation varies slightly for each platform. So I wont get into the actual installation details as for this article is focused on just a simple sockets.io and NodeJS framework example and just how little code it takes. First step, make sure the NodeJS framework is running and you have the node service running in your environment. Then all you have to do next is use the command line interface (CLI) of Node and run the following command..
npm install socket.io
From there node does the rest and acts like RPM in linux or cross platform git pull requests. It installs the packages required for socket.io into your server application project. Now the magic and fun begins! With a little bit of coding you just implement the following structure within your server code template.
var io = require('socket.io')(80ar cfg = require('./config.json');
var tw = require('node-tweet-stream')(cfg);
tw.track('socket.iotw.track('javascripttw.on('tweetunction(tweet){
  io.emit('tweetweet);
});
You now have a super basic framework to actually make those calls do something server-side! The combined frameworks would look a little something like the code below… when you implement them together. The code below will create a server, serve up an index.html page, and provide a method to send a string via a socket message to that page.
var app = require('http').createServer(handler)
var io = require('socket.io')(appar fs = require('fs');

app.listen(80);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Errording index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connectionunction (socket) {
  socket.emit('news hello: 'world' });
  socket.on('myer event', function (data) {
    console.log(data);
  });
});
Now you still have to deal with the client side handling. All we’ve done up to this point is create the handler on the server for those messages. If you start thinking outside of this example and instead of sending just a string.. you can send anything you want: database data, variable data stored from an incoming socket (like a chat app with messages going both directions), static data, basically anything you can program around. So lets setup the simple client side html to take our string and do something with it.
< script src="/socket.io/socket.io.js" >
  var socket = io('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
And thats it! You include the socket library into your page, instantiate a socket connection, and when the socket is received in the socket.on bit, you do something with it, in this instance log it to the console. It is a powerful framework once you get outside of the examples, these code examples are from both the documentation on NodeJS as well as Socket.io combined into one place. So far the apps I’ve made with NodeJS include a restaurant ordering kiosk that sends socket messages to android tablets that the waitresses carry with them which is out in the wild and deployed. An IP camera server that sends image data as a socket message back to an archival server for a railway system. Current NodeJS projects in development are: A kiosk system for tradeshows that enable quick and easy data exchange, and a multi-player mobile based game engine that I have been developing for some time now.

Published: September 21, 2015

Categories: NodeJS, Programming, Development, Real time data, Websockets

Tags:

Author: Nick Bagnoli