Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log the websocket traffic data through node http-proxy

I want to proxy websockets through http-proxy, I can log the receive data, but I can't get the send data from the proxy. how can I do ?

#!/usr/bin/env node

var wstarget = 'ws://localhost:8080/?r='+(Date.now() / 1000 | 0);

var httpProxy = require('http-proxy');
var http = require('http');

var proxy = httpProxy.createProxyServer({});

proxy.on('open', function (proxySocket) {
 proxySocket.on('data', function (data) {
    //console.log('\n'+data);
    console.log('',data);  // Just log the receive data! Can't get the Send data?
 });
});

var server = http.createServer();

server.on('upgrade', function (req, socket, head) {
  console.log("Proxying websocket connection to "+wstarget);
  proxy.ws(req, socket, head, {
   target: wstarget,
   changeOrigin: true,
   ws: true});
});

server.listen(8881);
like image 499
Y Rock Avatar asked May 23 '26 01:05

Y Rock


1 Answers

I found the answer !

 ...

 var WsParser = require('simples/lib/parsers/ws'); // npm install simples

 proxy.on('open', function (proxySocket) {
 proxySocket.on('data', function (data) {
    console.log('Down:'+data);
    console.log('',data);
 });

});

proxy.on('proxyReqWs', function(proxyReq, req, socket, options, head) {

    var parser = new WsParser(0, false);

    socket.pipe(parser);

    parser.on('frame', function (frame) {
      // handle the frame
      console.log('Up:',frame);
      console.log('Up data:'+frame.data);
      /*
        The structure of a frame:
        {
          data: buffer,
          fin: boolean,
          length: int,
          masked: boolean,
          opcode: int
        }
      */
    });

});

...
like image 122
Y Rock Avatar answered May 24 '26 16:05

Y Rock



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!