Node.js 相当于: echo 'message' | nc -v <服务器> <端口>

rsm*_*ets 5 javascript tcp tcpclient netcat node.js

尝试在 Node.js 应用程序中发送纯文本消息,就像我从终端使用“nc”发送纯文本消息一样,即

echo "a.random.test" | nc -v <some_domain> <some_port>
Run Code Online (Sandbox Code Playgroud)

然而却无法这样做。我尝试使用 const 'netcat/client' npm 模块,但没有成功。这是该模块的文档链接https://github.com/roccomuso/netcat,下面是我当前的一些尝试。似乎已建立连接(由于回调触发而确认),但是消息中存在额外的填充,并且我预期的“a.random.test”明文消息并未原样接收“a.random.test”。

const nclient = require('netcat/client')
const nc2 = new nclient()

nc2
.addr('x.x.x.x') // the ip
.port(2003) // the port 
.connect()
.send(`a.random.test`, () => console.log(`connection made and message sent`))
Run Code Online (Sandbox Code Playgroud)

我也尝试过下面好的“网络”模块插座,但没有成功。

var net = require('net');
var client = new net.Socket();

client.connect(2003, 'x.x.x.x', function() {
    console.log(`sending to server: a.random.test`)
    client.write(`a.random.test`)
});
Run Code Online (Sandbox Code Playgroud)

任何将纯文本发送到 Node.js 中给定端口的帮助都将不胜感激......我觉得这应该很容易 - 我花费的时间比我愿意承认的尝试这样做的时间要多!预先非常感谢您。

rob*_*lep 4

echo将换行符附加到字符串中,而您没有在 JS 代码中添加换行符:

var net = require('net');
var client = new net.Socket();

client.connect(2003, 'x.x.x.x', function() {
    console.log(`sending to server: a.random.test`)
    client.write(`a.random.test\n`)
                               ^^
});
Run Code Online (Sandbox Code Playgroud)

  • 哇谢谢你!我的尾巴现在将在我的两腿之间一段时间......再次感谢。 (2认同)