Node Connecting a JS Server to a Server

Is it possible to connect to a NodeJS server from another server? Do two NodeJS servers communicate 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... 
+6
source share
2 answers

Here is a simple example that creates a server and a client that connects to this server. Remember that what you send must be a buffer (lines are automatically converted to buffers). The client and server work independently of each other, so they can be placed in the same application or on completely 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 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 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 implement the Stream interface.

+11
source

Check Subclass dnode . It automatically maps literal objects from 1st env to 2nd. You get a kind of RPC out of the box. And it also works in the browser ...

0
source

All Articles