嘿,我正在写一个应用程序。我要求客户端输入某些消息,具体取决于我从服务器向客户端发送数据时收到的消息。当用户从客户端输入数据时,会发生响应,客户端再打印一次“输入消息”...我正在使用node.js的readline和net模块。这是我的代码:
var server = net.createServer( //My server side code which sends response.
function(socket){
console.log("Client connection...");
socket.on('end', function(){
console.log("Client disconnected...");
});
socket.on('data', function(data){
console.log(" Received: ", data.toString());
a=data.toString();
if(a=="lookupByLastName Smith") //json data send if client sends this
{
arr= employees.lookupByLastName('Smith');
socket.write("Data"+JSON.stringify(arr));
}
});
socket.write("Hello from server");
});
//客户端代码:
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var readMessage = function(client) {
rl.question("Enter Message: ", function (line){
client.write(line);//enter message appears twice before server res.
if (line == "bye")
client.end();
else
readMessage(client);
});
};
var client = net.connect({port:3000},
function(){
console.log("Connected to server");
readMessage(client);
});
client.on('end', function(){
console.log("Client disconnected...");
return;
});
client.on('data', function(data){
console.log("\n --Received:", data.toString());
});
Check the second message "Enter message" it shouldn't appear second time till server responds back。解决问题需要帮助。
答案 0 :(得分:0)
您可以在从服务器收到数据时询问用户输入。
在下面的示例中,我还为服务器问候消息添加了一些超时,以及当服务器没有响应客户端消息4秒时:
var readline = require('readline');
var net = require('net');
var port = 3000;
var helloTimeout;
var responseTimeout;
var timeout = 4000;
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var readMessage = function(client) {
rl.question("Enter Message: ", function(line) {
client.write(line); //enter message appears twice before server res.
if (line == "bye") {
client.end();
} else {
responseTimeout = setTimeout(function() {
console.log('not response from server for ' + timeout + "ms");
client.emit("wait_for_input");
}, timeout);
}
});
};
var client = net.connect({ port: port },
function() {
console.log("Connected to server");
helloTimeout = setTimeout(function() {
console.log('no hello received for ' + timeout + "ms, closing ...");
client.end();
}, timeout);
});
client.on('end', function() {
console.log("Client disconnected...");
rl.close();
});
client.on('wait_for_input', function() {
readMessage(client);
});
client.on('data', function(data) {
clearTimeout(helloTimeout);
clearTimeout(responseTimeout);
console.log("\n --Received:", data.toString());
client.emit("wait_for_input");
});
我创建了一个名为client
的{{1}}的另一个事件,只有在数据来自服务器(计算此数据之后)并且客户端没有收到服务器响应超过4秒后才会触发用户输入一些命令后