NodeJS实现websocket代理机制

Roy 2018-04-15 01:46117 阅读
  • 使用的模块
    • ws
    • http
    • http-proxy
  • 主要通过htt-proxy实现中转

  • 启动websocket服务
var WebSocketServer = require('ws').Server;
var wss             = new WebSocketServer({port: 6443});

console.log(6443);
wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
        console.log('received: %s', message);
        ws.send(message);
    });
});

wss.on('error', function (error) {
    console.log('error:', error);
});

 

  • 启动http-proxy代理服务器

  注意:客户端发送的数据websocket已加密无法直接获得,该演示通过ws模块中的PerMessageDeflate实现解密。黄色区域代码请自行调整

const http              = require('http');
const httpProxy         = require('http-proxy');
const ws                = require('ws');
const Receiver = ws.Receiver; const Extensions = ws.Extensions; const PerMessageDeflate = ws.PerMessageDeflate;
const proxy             = new httpProxy.createProxyServer({target: 'ws://localhost:6443', ws: true});
const proxyServer       = http.createServer(function(req, res) {
    proxy.web(req, res);
});

proxyServer.on('upgrade', function(req, socket, head) {
    let extensions        = {};
    let perMessageDeflate = new PerMessageDeflate({}, true);
    let serverExtensions  = Extensions.parse(req.headers['sec-websocket-extensions']);
    perMessageDeflate.accept(serverExtensions[PerMessageDeflate.extensionName]);
    extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
    let _receiver                               = new Receiver(extensions, 0);

    socket.on('data', function(data) {
        _receiver.add(data);
    });

    _receiver.ontext = function ontext(data, flags) {
        console.log('客户端请数据:', data);
    };

    _receiver.onclose = function onclose(code, data, flags) {
        console.log('onclose:', data);
    };

    _receiver.onerror = function onerror(reason, errorCode) {
        console.log('onerror:', reason);
    };

    proxy.ws(req, socket, head);
});

proxyServer.on('error', function(error) {
    console.log('error:', error);
});

proxy.on('open', function(proxySocket) {
    let extensions        = {};
    let perMessageDeflate = new PerMessageDeflate({}, true);
    let serverExtensions  = Extensions.parse(proxySocket._httpMessage._headers['sec-websocket-extensions']);
    perMessageDeflate.accept(serverExtensions[PerMessageDeflate.extensionName]);
    extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
    let _receiver                               = new Receiver(extensions, 0);

    proxySocket.on('data', function(data) {
        _receiver.add(data);
    });

    _receiver.ontext = function ontext(data, flags) {
        console.log('代理服务器返回数据:', data);
    };
});

proxyServer.listen(8080);
  • 代理服务器日志:

    客户端请数据: 222222

    代理服务器返回数据: 222222

    客户端请数据: client----1

    代理服务器返回数据: client----1

    客户端请数据: client----2

    代理服务器返回数据: client----2

回复数量: 0
暂无评论~~
  请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!