Sunday, March 16, 2014

Node.js app using Socket.IO

Socket.IO aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms. It's care-free realtime 100% in JavaScript.

This example create a simple web app to receive the status of a toggle button from client.


Before using Socket.IO on your Node.js app, run the command to install:
$ npm install socket.io

app.js run in server side:
//$ npm install socket.io

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(8080);

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);
  });
}

io.sockets.on('connection', function (socket) {
  socket.on('button update event', function (data) {
    console.log(data.status);
  });
});

index.html, it will be sent to and run on client side.
<html>
<head></head>
<body>
<hi>Test Node.js with socket.io</hi>
<form action="">
<input type="button" id="buttonToggle" value="ON" style="color:blue"
       onclick="toggle(this);">
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.href);

function toggle(button)
{
 if(document.getElementById("buttonToggle").value=="OFF"){
  document.getElementById("buttonToggle").value="ON";
  socket.emit('button update event', { status: 'OFF' });
 }
 else if(document.getElementById("buttonToggle").value=="ON"){
  document.getElementById("buttonToggle").value="OFF";
  socket.emit('button update event', { status: 'ON' });
 }
}
</script>

</body>
</html>

Run the app.js in server:
$ node app

Visit <server IP>:8080 with browser in client side.


Next: Acknowledge from server

No comments: