我想通过http代理代理websocket,我可以记录接收数据,但是我无法从代理获取发送数据。我该怎么办?
#!/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);
我找到答案了!
...
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
}
*/
});
});
...
这里使用 ws lib 而不是 simples
const {Receiver} = require('ws');
const server = require('http').createServer().listen(3000);
const proxy = require('http-proxy').createProxyServer({ws: true});
server.on('upgrade', function (req, socket, head) {
proxy.ws(req, socket, head);
proxy.on('proxySocket', function (socket) {
const r = new Receiver();
r.on('message', (msg) => {
console.log('message', msg.toString());
});
socket.pipe(r);
});
});