How to connect two node.js servers with websockets?

For future people:
Here is 2 very simple Node.js apps that use socket.io to connect, send and receive messages between each other.

Required package is:

npm install socket.io

Node-App-1 server.js:

var io = require('socket.io').listen(3000);
io.on('connection', function (socket) {
    console.log('connected:', socket.client.id);
    socket.on('serverEvent', function (data) {
        console.log('new message from client:', data);
    });
    setInterval(function () {
        socket.emit('clientEvent', Math.random());
        console.log('message sent to the clients');
    }, 3000);
});

Node-App-2 client.js:

var io = require('socket.io-client');
var socket = io.connect("http://localhost:3000/", {
    reconnection: true
});

socket.on('connect', function () {
    console.log('connected to localhost:3000');
    socket.on('clientEvent', function (data) {
        console.log('message from the server:', data);
        socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
    });
});

Leave a Comment

tech