Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS Server to Server Connection

Is it possible to connect to a NodeJS Server from another server? Two NodeJS servers communicating with each other?

//Server Code
var io = require('socket.io').listen(8090);

io.sockets.on('connection', function (socket) {
io.sockets.emit('this', { will: 'be received by everyone'});

socket.on('private message', function (from, msg) {
   console.log('I received a private message by ', from, ' saying ', msg);
});

socket.on('disconnect', function () {
   io.sockets.emit('user disconnected');
  });
});

//Client Code in Server Code. Connecting to another server.
io.connect( "http://192.168.0.104:8091" );  //Connect to another server from this one.

//ETC...
like image 576
Taurian Avatar asked Jan 01 '13 18:01

Taurian


1 Answers

Here's a simple example that creates a server and a client that connects to that server. Remember that what you send has to be a buffer (strings are automatically converted to buffers). The client and server works independently of eachother, so can be put in the same app or on totally different computers.

Server (server.js):

const net = require("net");

// Create a simple server
var server = net.createServer(function (conn) {
    console.log("Server: Client connected");

    // If connection is closed
    conn.on("end", function() {
        console.log('Server: Client disconnected');
        // Close the server
        server.close();
        // End the process
        process.exit(0);
    });

    // Handle data from client
    conn.on("data", function(data) {
        data = JSON.parse(data);
        console.log("Response from client: %s", data.response);
    });

    // Let's response with a hello message
    conn.write(
        JSON.stringify(
            { response: "Hey there client!" }
        )
    );
});

// Listen for connections
server.listen(61337, "localhost", function () {
    console.log("Server: Listening");
});

Client (client.js):

const net = require("net");

// Create a socket (client) that connects to the server
var socket = new net.Socket();
socket.connect(61337, "localhost", function () {
    console.log("Client: Connected to server");
});

// Let's handle the data we get from the server
socket.on("data", function (data) {
    data = JSON.parse(data);
    console.log("Response from server: %s", data.response);
    // Respond back
    socket.write(JSON.stringify({ response: "Hey there server!" }));
    // Close the connection
    socket.end();
});

The conn and socket objects both implement the Stream interface.

like image 87
mekwall Avatar answered Nov 03 '22 06:11

mekwall