Tuesday, 29 August 2023

Capturing data written to a Node.js socket

The 'data' event from net.Socket can be used to read data received from a socket, for example:

const net = require('net');

const server = net.createServer((socket) => {
  socket.on('data', (buffer)=>{
    console.log(`Server received ${buffer}`)
    socket.write('World');
  });
});
server.listen(8080, '127.0.0.1');

const socket = new net.Socket();
socket.on('data', (buffer) => {
  console.log(`Client received ${buffer}`)
});
socket.connect(8080, '127.0.0.1');

setTimeout(()=>{
  socket.write('Hello');
},100);
setTimeout(()=>{
  socket.write('Hi');
},200);

setTimeout(()=>{
  console.log('Goodbye.');
  socket.destroy();
  server.close();
},300);

Prints:

Server received Hello
Client received World
Server received Hi
Client received World
Goodbye.

Is there a way read data sent out from a socket? For example if server was a remote server, is there a way to capture the data sent to the server from the socket using events or any another method?



from Capturing data written to a Node.js socket

No comments:

Post a Comment