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

时间:2013-01-01 18:54:01

标签: node.js client socket.io

是否可以从另一台服务器连接到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...

2 个答案:

答案 0 :(得分:12)

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

服务器(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接口。

答案 1 :(得分:0)

检查Substrack's dnode。它自动映射从第一个env到第二个env的文字对象。你获得了一种开箱即用的RPC。它也适用于浏览器......