我有两个客户端将连接到我的服务器。我有以下代码来设置服务器,然后客户端将运行命令
在他们的终端上telnet localhost 3000。现在这部分可以工作了
var http = require('http');
var net = require('net')
var listOfClients = []
var server = net.createServer(function(socket) {
socket.write("Welcome to ROCK PAPER SCISSORS choose from the following \n")
socket.write("[1] Rock \n")
socket.write("[2] Paper \n")
socket.write("[3] Scissors \n")
listOfClients.push(socket)
server.getConnections(function(error, count) {
if (count == 2) {
let p1 = listOfClients[0].on('data', function(data) {
return data;
});
let p2 = listOfClients[1].on('data', function(data) {
return data;
});
console.log(p1)
console.log(p2)
}
});
});
然后客户选择1或2或3作为石头/剪刀/布我想将他们使用的内容保存在变量中,但是方法
let p1 = listOfClients[0].on('data', function(data) {
return data;
});
不会将数据保存到变量中并返回很多我不理解的内容。关于如何做到这一点有什么想法吗?我在列表中有套接字,只需要它们将客户端输入保存到变量中。
最佳答案
NodeJS 使用 events 工作。 根据文档:
Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called "emitters") emit named events that cause Function objects ("listeners") to be called.
在您的代码中,listOfClients[0].on('data'...
代码片段实际上是为事件“data”创建监听器。
本质上,您是在告诉代码:嘿,您可以继续听这些内容并在发生时执行某些操作吗?
在您的代码中,您告诉它“当客户端[0]发送一些数据时执行某些操作”。
所以当你写:
const variableName = something.on('someEvent', function(data) {});
变量variableName
实际上是接收事件监听器的结果并使用回调作为第二个参数。
让我们编写一个快速函数,其中有一个参数作为回调:
function myFunction(data, callback) {
callback("This is where you're trying to return the value");
return 'this is the event listener return';
}
const myVar = myFunction('Anything you please', function(callbackResult) {
console.log(`This is the callback: ${callbackResult}`);
});
console.log(`This is the var value: ${myVar}`);
运行上述代码将输出:
node v10.15.2 linux/amd64
This is the callback: This is where you're trying to return the value
This is the var value: this is the event listener return
解决您问题的一种方法是将数据分配给事件监听器外部的变量,如下所示:
const storeHere = [];
function myFunction(data, callback) {
callback("This is where you're trying to return the value");
return data;
}
const myVar = myFunction('Anything you please', function(callbackResult) {
storeHere.push(callbackResult); // Store somewhere outside
});
console.log(`This is the externalVar value: ${storeHere}`);
console.log(`This is the var value: ${myVar}`);
关于javascript - 将两个客户端数据保存到一个变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55973376/