1

我正在向自定义协议 TCP 服务器发出换行符分隔的文本命令。在下面的示例中,我发出 2 个命令并收到回写的响应。它在 telnet 和 netcat 中按预期工作:

$ nc localhost 1234
command1
command2
theresponse

与 Node.js 连接时,相同的工作流程不起作用:

var net = require('net');
var client = net.connect(1234, 'localhost');

client.on('data', function(data) {
    console.log('data:', data.toString());
});

client.on('error', function(err) {
    console.log('error:', err.message);
});

client.write('command1\n');
client.write('command2\n');

我希望在运行该程序后,我会看到“数据:响应”写入控制台,但是,没有打印任何内容。我也尝试在“连接”回调中执行写入,但结果相同。奇怪的是,当我在 Node REPL 中尝试这个时......它可以工作:

$ node
> var net = require('net')
undefined
> var client = net.connect(1234, 'localhost')
undefined
> client.on('data', function(data) { console.log('data:', data.toString()); })
{ ... }
> client.write('command1\n')
true
> client.write('command2\n')
true
> data: theresponse

有人对这种奇怪的行为有想法吗?

谢谢。

-斯科特

4

1 回答 1

2

在不测试代码的情况下,我假设是 Node.js 的异步特性让您感到厌烦。在 REPL 中,连接发生在您输入另一个命令之前。在上面的代码中,您是在连接之前编写的。

把上面的代码改成这样:

var net = require('net');
var client = net.connect(1234, function(){
   client.on('data', function(data) {
     console.log('data:', data.toString());
   });

   client.on('error', function(err) {
     console.log('error:', err.message);
   });

   client.write('command1\n');
   client.write('command2\n');
});
于 2012-05-23T19:09:07.550 回答