我有两个将要连接到我的服务器的客户端。我有以下代码来设置服务器,然后客户端将运行命令
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;
});
不会将数据保存到变量中,并且返回很多我不了解的东西。有关如何执行此操作的任何想法?我在列表中有套接字,只需要它们将客户端输入保存到变量中即可。
答案 0 :(得分:2)
NodeJS使用events工作。 根据文档:
大部分Node.js核心API都是基于惯用的异步事件驱动的体系结构,在该体系结构中,某些类型的对象(称为“发射器”)发出命名事件,这些事件导致调用功能对象(“侦听器”)。 / p>
在您的代码中,class Expression:
def __init__(self, form, sort, head, val):
self.form = form
self.sort = sort
self.head = head
self.val = val
#Removed the superclass reference
class Head:
def __init__(self, pos, agr):
self.pos = pos
self.agr = agr
agr_pos = ['n', 'd', 'v', 'a', 'pn']
if self.pos not in agr_pos:
self.agr = None
#Removed the superclass reference
class Agr:
def __init__(self, agr_info):
self.per = agr_info[0]
self.num = agr_info[1]
self.gen = agr_info[2]
self.case= agr_info[3]
self.det = agr_info[4]
self.svagr = self.per + self.num + self.case
self.npagr = self.num + self.gen + self.case + self.det
#Removed the superclass reference
class Val:
def __init__(self, spr, comps):
self.spr = spr
self.comps = comps
form = 'von'
pos = 'p'
agr = None
spr = 'underspecified'
comps = 'NP_3'
#Used variable assignment here instead of exec and used a new variable expr
expr = Expression(form, "word", Head(pos, agr), Val(spr, comps))```
代码段实际上是在为事件“数据”创建一个侦听器。
从本质上讲,您是在告诉代码:嘿,您能继续听那些话,并在发生时做些什么吗?
在您的代码中,您要告诉它“在客户端[0]发送一些数据时执行某些操作”。
所以当您写:
listOfClients[0].on('data'...
实际上,变量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