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

Tau*_*ian 6 client node.js 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...
Run Code Online (Sandbox Code Playgroud)

mek*_*all 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");
});
Run Code Online (Sandbox Code Playgroud)

客户端(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();
});
Run Code Online (Sandbox Code Playgroud)

connsocket对象都实现了Stream接口.