const http = require('http') const server = http.createServer((req, res) =>{ res.end('hello world'); }).listen(8080) server.on('upgrade', (req, client, head) => { const headers = _getProxyHeader(req.headers) //將客戶端的websocket頭和一些信息轉發到真正的處理服務器上 headers.hostname = 'localhost'//目標服務器 headers.path = '/' 目標路徑 headers.port = 6443 const proxy = http.request(headers) //https可用https,headers中加入rejectUnauthorized=false忽略證書驗證 proxy.on('upgrade', (res, socket, head) => { client.write(_formatProxyResponse(res))//使用目標服務器頭信息響應客戶端 client.pipe(socket) socket.pipe(client) }) proxy.on('error', (error) => { client.write("Sorry, cant't connect to this container ") return }) proxy.end() function _getProxyHeader(headers) { const keys = Object.getOwnPropertyNames(headers) const proxyHeader = { headers: {} } keys.forEach(key => { if (key.indexOf('sec') >= 0 || key === 'upgrade' || key === 'connection') { proxyHeader.headers[key] = headers[key] return } proxyHeader[key] = headers[key] }) return proxyHeader } function _formatProxyResponse(res) { const headers = res.headers const keys = Object.getOwnPropertyNames(headers) let switchLine = '\r\n'; let response = [`HTTP/${res.httpVersion} ${res.statusCode} ${res.statusMessage}${switchLine}`] keys.forEach(key => { response.push(`${key}: ${headers[key]}${switchLine}`) }) response.push(switchLine) return response.join('') } })
暫時沒有問題,如遇到歡迎指出。