Sunday, 8 April 2012

Node.js application using 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 on the server

Creating the server
var http = require('http'),
    io = require(''),
    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>');

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) {
    }, 500, 'From server...');

Client code
<!DOCTYPE html>
    <script src="//"></script>
    <script src="socket/"></script>
        var socket = new io.Socket();

        socket.on('connect', function () {
        socket.on('message', function (data) {
        socket.on('disconnect', function () {
        socket.on('customEvent', function (message) {
    <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>

No comments:

Post a Comment