我有两个将要连接到我的服务器的客户端。我有以下代码来设置服务器,然后客户端将运行命令
在其终端上使用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进行工作。
根据文档:
Node.js核心API的大部分都基于惯用的异步事件驱动的体系结构,在该体系结构中,某些类型的对象(称为“发射器”)发出命名事件,这些事件导致调用功能对象(“侦听器”)。
在您的代码中,代码的listOfClients[0].on('data'...
代码段实际上是为事件“数据”创建一个侦听器。
从本质上讲,您是在告诉代码:嘿,您能继续听那些声音,并在发生这种情况时做些什么吗?
在您的代码中,您要告诉它“在client [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/