Sunday, 8 April 2012

Node.js application using Socket.io


Socket.io provides real-time communication between your node.js server and clients. Socket.IO allows you to emit and receive custom events. Besides `connect`, `message` and `disconnect`, you can emit custom events also.
The socket can be created by the user and used as a client (with connect()) or they can be created by Node and passed to the user through the 'connection' event of a server.

Installing socket.io on the server

Creating the server
var http = require('http'),
    io = require('socket.io'),
    sys = require('util'),
    express = require('express');

var port = 8083;
var server = express.createServer(function (req, res) {

    // Send HTML headers and message
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('<h1>Socket server...</h1>');
});
server.listen(port);

var socket = io.listen(server);

socket.sockets.on('connection', function (client) {
    client.on('message', function (data) {
        console.log('Message received: ' + data);
    });
    client.on('disconnect', function () {
        console.log('Disconnected from server!!!');
    });
    var intervalId = setInterval(function (message) {
        client.send(message);
    }, 500, 'From server...');
});

Client code
<!DOCTYPE html>
<html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="socket/socket.io.js"></script>
    <script>
        var socket = new io.Socket();
        socket.connect('http://localhost:8083');


        socket.on('connect', function () {
            $('#status').text('Connected');
        });
        socket.on('message', function (data) {
            $('#message').text(data);
        });
        socket.on('disconnect', function () {
            $('#status').text('Disconnected');
        });
        socket.on('customEvent', function (message) {
            $('#customEvent').text(message['time']);
        });
       </script>
  </head>
  <body>
    <h1>WebSocket Test</h1>
    <h2>Status: <span id="status">Waiting</span></h2>
    Received using client.send <pre id="message"></pre>
    <hr />   
    Received using client.emit <pre id="customEvent"></pre>
  </body>
</body>

No comments:

Post a Comment