First steps with WebSocket and Node.js (and Socket.io)

Demo of sending notification to a web page by WebSocket with Node.js, this remotely or locally.

We will see that with WebSocket, it is easy to create an HTML 5 interface for a local application. Other applications are also possible such as the remote control of a robot.

on and emit

The  socket.io API contains two methods for exchanging data that both run client side or server side, emit and on. Other methods are used to start the connection.

emit
Sending data. Its setting a code such as "notification", and the other party responds to this request through a method that has the same code.
on
Responds to the sending of data from the other party and calls a function, given as a parameter, to process this data.
connect
Starts a connection to the server, at the client request. It may have the server name as parameter, by default there is no argument.
listen
Creates a listener, a function that intercepts the request from the client.

The interface script first creates a server object and a socket.io object, then a listener. It sends the a HTML page to the client.

The web page when displayed on the client side creates a socket object and start the connection:

var socket = io.connect();

socket.on('notification', function(x) { notification(x); });

The notification function is a handler who is awaiting a response from the server, and processes the data that the server sends. In our example, the processing is to put the data received in a layer whose id is "storage".

The server intercepts the client request with the function on:

listener.sockets.on('connection', function (socket) { start(socket);} ); 

It confirms it received it with a emit command:

socket.emit('notification', 'Server online via socket!'); 

All this occurs at page load. Now we will see how to get a real interaction between the user and the server.

Interaction with the server

If we want real interaction, the page must send a request to the server at the request of the user, and displays the data transmitted by the server in response.

To demonstrate this, we add a button on the page. When the user presses this button, the callserver JavaScript function is executed.
The HTML page then starts the exchange with the server side script with a command emit.

socket.emit('called', 'Nothing'); 

The server intercepts the request and in response to the command 'called', sends a new message. This message is a set of data in JSON format that we have replaced here with a string:

socket.emit('notification', 'Yes still here! Want some data?');

On the client side, it is always the same handler that receives the data and displays the contents.

socket.on('notification', function(x) { notification(x); });	

In practice, the content will be a set-key values, keys corresponding for example to text fields in the HTML page and values being contents to be displayed.

Here is the complete source code of both files ...

The server side script, socket-mini.js

var uri="/socket-mini.html";
var fs = require('fs'),
    http = require('http'),
    socket = require("socket.io");

var page = fs.readFileSync(__dirname + uri);

function handler(request, response)
{
  response.write(page);
  response.end();
}
var app = http.createServer(function(r, s){ handler(r,s); });
app.listen(1000);
var listener = socket.listen(app, { log: false });

function start(socket)
{
  socket.emit('notification', 'Server online via socket!');
  socket.on('called', function(){
    console.log("Request received.");
    listener.sockets.emit('notification', 'Yes still here! Want some data?');
});
}
listener.sockets.on('connection', function (socket) { start(socket);} );

To start the server, type at command line:

node socket-mini.js

The server responds to only two types of queries, 'connection' and 'called', the first being preset, the second having been created by our demonstration.
You can create as many types of queries you want. If you want to avoid defining a function to each, they can be placed in the data sent with 'called' an array of key-value, each key being a control and each value providing the parameters for it.

The client side script, socket-mini.html

<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title></title>
</head>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect();

function notification(content)
{
  var x= document.getElementById("storage");
  x.innerHTML = content;
  console.log(content);
}

socket.on('notification', function(x) { notification(x); });

function callserver()
{
  socket.emit('called', 'Nothing');
}
</script>

<body>
<h1>Notification from server by socket.io</h1>
<fieldset><legend>Messages received</legend>
<div id="storage"></div>
</fieldset>

<form name="form1" method="post" action="">
<input type="button"  value="Call server" onClick="callserver()">
</form>
</body>
</html>

This page is send by the server and displayed by the browser when you type in the URL bar of the browser:

localhost:1000

This demonstration is limited to a single HTML page given as parameter to the server and assigned to the variable uri, (which is enough to create an application with HTML interface).
Based on the previous tutorials, including How to build a page and application server script, you can make it more generic and use different HTML pages with the same server-side script. A such tool will be offered on that site in the future.

For this article only the files socket-mini.html and socket mini.js are required.