如何拦截节点中传出的 tcp 消息?
How do I intercept outgoing tcp messages in node?
如何编写拦截消息的简单流?
例如,假设我想记录(或最终转换)通过用户的 socket.write(...) 呼叫通过网络发送的消息。
以下是尝试执行此操作的最小程序:
const net = require('net');
const stream = require('stream');
const socket = new net.Socket();
const transformer = new stream.Transform({
transform(chunk,e,cb){
console.log("OUT:"+chunk.toString());
cb();
}});
//const client = socket.pipe(transformer); // <= prints "OUT:" on client, but nothing on server
const client = transformer.pipe(socket); // <= prints nothing on client, but "hello world" on server
socket.on('data', (data)=>{ console.log("IN:"+data.toString()); });
socket.connect(1234, 'localhost', ()=>{ client.write("hello world"); });
当我执行 socket.pipe(transformer) 时,客户端会打印 "OUT:"(如我所愿),但实际上不会向服务器发送任何内容。当我交换管道位置时,transformer.pipe(socket),没有任何内容打印到客户端,但消息被发送到服务器。
虽然这里没有列出,但我也尝试使用可写流,它会在客户端打印消息,但它永远不会发送到服务器(如果我执行 this.push(... ) 在可写流中,它似乎仍然没有发送到服务器)
我在这里错过了什么?
编辑:为清晰起见重新格式化代码并更新文本
您没有从流中写入任何数据。
您需要 this.push(chunk)
或将对 cb
的调用更改为 cb(null, chunk)
。
See the docs about implementing transform streams for more info.
看来我需要更改以下行
socket.connect(1234, 'localhost', ()=>{ client.write("hello world"); });
至此
socket.connect(1234, 'localhost', ()=>{ transformer.write("hello world"); });
这是基于@Mr.Phoenix的评论。我希望 .pipe() 到 return 一个我可以使用的新流。我相信这就是 Java 的 netty 框架的工作方式,我一直期望节点流以相同的方式工作。
如何编写拦截消息的简单流?
例如,假设我想记录(或最终转换)通过用户的 socket.write(...) 呼叫通过网络发送的消息。
以下是尝试执行此操作的最小程序:
const net = require('net');
const stream = require('stream');
const socket = new net.Socket();
const transformer = new stream.Transform({
transform(chunk,e,cb){
console.log("OUT:"+chunk.toString());
cb();
}});
//const client = socket.pipe(transformer); // <= prints "OUT:" on client, but nothing on server
const client = transformer.pipe(socket); // <= prints nothing on client, but "hello world" on server
socket.on('data', (data)=>{ console.log("IN:"+data.toString()); });
socket.connect(1234, 'localhost', ()=>{ client.write("hello world"); });
当我执行 socket.pipe(transformer) 时,客户端会打印 "OUT:"(如我所愿),但实际上不会向服务器发送任何内容。当我交换管道位置时,transformer.pipe(socket),没有任何内容打印到客户端,但消息被发送到服务器。
虽然这里没有列出,但我也尝试使用可写流,它会在客户端打印消息,但它永远不会发送到服务器(如果我执行 this.push(... ) 在可写流中,它似乎仍然没有发送到服务器)
我在这里错过了什么?
编辑:为清晰起见重新格式化代码并更新文本
您没有从流中写入任何数据。
您需要 this.push(chunk)
或将对 cb
的调用更改为 cb(null, chunk)
。
See the docs about implementing transform streams for more info.
看来我需要更改以下行
socket.connect(1234, 'localhost', ()=>{ client.write("hello world"); });
至此
socket.connect(1234, 'localhost', ()=>{ transformer.write("hello world"); });
这是基于@Mr.Phoenix的评论。我希望 .pipe() 到 return 一个我可以使用的新流。我相信这就是 Java 的 netty 框架的工作方式,我一直期望节点流以相同的方式工作。