节点JS服务器到服务器连接

是否有可能从另一台服务器连接到NodeJS服务器? 两个NodeJS服务器相互通信?

//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... 

       

网上收集的解决方案 "节点JS服务器到服务器连接"

下面是一个简单的例子,它创build一个服务器和一个连接到该服务器的客户端。 请记住,您发送的内容必须是缓冲区(string会自动转换为缓冲区)。 客户端和服务器彼此独立工作,因此可以放在同一个应用程序或完全不同的计算机上。

服务器(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.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(); }); 

connsocket对象都实现Stream接口。

检查Substrack的dnode 。 它自动映射从第一个env到第二个的文字对象。 开箱即可获得一种RPC。 它也可以在浏览器中运行