Example Socket.IO client and server

Here is a basic example of a WebSocket client and server using the popular Socket.IO framework.

The main advantage of using Socket.IO vs writing your own WebSocket client and server is that Socket.IO will fall back to other protocols if your WebSocket connection fails for some reason (e.g. proxies that don't support HTTP 1.1).

Install the NPM package:

npm install socket.io

Create example.js with the following contents:

var http = require('http');
var ioServer = require('socket.io');
var port = 10001;

// SERVER
var webServer = http.createServer();
var socketServer = ioServer(webServer);

socketServer.on('connection', function (socket) {
    console.log('client connected');

    socket.on('PING', function () {
        console.log('PING');
        socket.emit('PONG');
    });

    socket.on('disconnect', function () {
        console.log('client disconnected');
        webServer.close();
    });
});

webServer.listen(port);

// CLIENT
var io = require('socket.io-client');
var client = io('http://localhost:' + port);

client.on('connect', function () {
    client.emit('PING');
});

client.on('PONG', function () {
    console.log('PONG');
    client.close();
});

Run the example:

$ node example.js

You should see the following output:

client connected
PING
PONG
client disconnected

To use the client code in the browser you will first need to load Socket.IO from the server:

<script src="/socket.io/socket.io.js"></script>

And then create the client using:

var client = io(location.host);

Docs