使用的模塊 ws http http-proxy 主要通過htt-proxy實現中轉 啟動websocket服務 ws http http-proxy 啟動http-proxy代理伺服器 註意:客戶端發送的數據websocket已加密無法直接獲得,該演示通過ws模塊中的PerMessageDefla ...
- 使用的模塊
- 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