NodeJS實現websocket代理機制

有我在發表於2018-04-13
  • 使用的模組
    • 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

相關文章