gpt4 book ai didi

node.js - Node JS 服务器到服务器连接

转载 作者:搜寻专家 更新时间:2023-10-31 22:28:14 24 4
gpt4 key购买 nike

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

最佳答案

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

服务器(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界面。

关于node.js - Node JS 服务器到服务器连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14113254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com