Example 5: Socket IO App

This example will show you how to create a socket IO server and client using Node.js , it will demonstrate how to setup a socket IO server, and how to send socket message to server.

Let’s try creating below folders:

example under {your_node.js_installed_path}\nodejs\
demo5 under {your_node.js_installed_path}\nodejs\examples\

 

Then, create below 2 js files under {your_node.js_installed_path}\nodejs\examples\demo5\ :

server.js // Define socket IO

var io                                     = require(‘socket.io’)();

var _socket                        = ”;

 

//When new client is connected

io.on(‘connection’, function (socket) {

console.log(‘hello… you are connected (id=’ + socket.id + ‘).’);

_socket = socket;

 

//Receiving incoming message ‘message_reply’

socket.on(‘message_reply’, function(msg) {

console.info(‘message_reply : ‘+msg);

});

 

//When disconnect

socket.on(‘disconnect’, function() {

console.info(‘Socket id=’ + _socket.id + ‘ has gone.’);

});

});

 

// Listening to port 3000 for new connection and incoming message

io.listen(3000, function () {

console.log(‘Demo 5 – server with port : 3000’);

});

 

// Auto-send message to client every 5s

setInterval(function() {

var currentTime = new Date().toISOString();

console.log(‘Ping client : ‘+_socket.id+’ msg #’+currentTime);

_socket.emit(‘ping_client’, ‘Ping client : ‘+_socket.id+’ msg #’+currentTime);

}, 5000);

sender.js // Define client socket IO

var io                     = require(‘socket.io-client’);

var client              = io.connect(‘http://localhost:3000’);

 

//Receiving incoming message ‘ping_client’

client.on(‘ping_client’, function(msg) {

console.info(‘Receiving ping message from server : ‘+msg);

 

//Send message to server

client.emit(‘message_reply’, ‘Hi server, got your message’);

console.info(‘Sending ack message to server’);

});

 

Or, you can download here.

Let’s try to run the application and see what’s happening:

Server – socket.io

  1. run “cmd”
  2. cd {your_node.js_installed_path}\nodejs\
  3. node examples/demo5/server.js

 

Sender – socket.io

  1. run “cmd”
  2. cd {your_node.js_installed_path}\nodejs\
  3. node examples/demo5/sender.js

 

Yeap!!! It’s done.

After all these examples, hope that you can have a brief introduction to Node.js . However, before working on Node.js for your project, you better understand the pros and cons (good for and bad for) of Node.js – you can reference to the Introduction of this blog. Otherwise, your Node.js application may not work as you expected.

Please rate this