Thursday, 27 April 2017

How do I intercept outgoing tcp messages in node?

How can I write a simple stream which intercepts messages?

For example, say I want to log (or eventually transform) a message being sent over the wire by a user's socket.write(...) call.

Following is a minimal program which attempts to do this:

const net    = require('net');
const stream = require('stream');

const socket = new net.Socket();
const client = socket.pipe(new stream.Transform({write(chunk,e,cb){console.log("OUT:"+chunk.toString());cb();}}).pipe(socket));
//const client = (new stream.Transform({write(chunk,e,cb){console.log("OUT:"+chunk.toString());cb();}}).pipe(socket)).pipe(socket);

socket.on('data', (data)=>{ console.log("IN:"+data.toString()); });
socket.connect(1234, 'localhost', ()=>{ client.write("hello world"); });

Notice that I have tried socket.pipe(transformstream...) as well as transformstream.pipe(socket). In both cases, the messages is sent to the server, but no "OUT:" message is every printed by the client.

Although not listed here, I also tried to use the Writable stream, which does print the message on the client, but it is never sent to the server (if I do a this.push(...) inside the Writable stream, it still doesn't seem to send to the server)

What am I missing here?



via Shahbaz

No comments:

Post a Comment