diff --git a/lib/node-http-proxy/http-proxy.js b/lib/node-http-proxy/http-proxy.js index 1a893f8de..4c1ff564c 100644 --- a/lib/node-http-proxy/http-proxy.js +++ b/lib/node-http-proxy/http-proxy.js @@ -694,6 +694,15 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, head, buffer) socket: socket, head: head }; + + // + // Here we set the handshake `headers` and `statusCode` data to the outgoing + // request so that we can reuse this data later. + // + reverseProxy.handshake = { + headers: {}, + statusCode: null, + } // // If the agent for this particular `host` and `port` combination @@ -703,7 +712,16 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, head, buffer) // In addition, it's important to note the closure scope here. Since // there is no mapping of the socket to the request bound to it. // - reverseProxy.on('upgrade', function (_, remoteSocket, head) { + reverseProxy.on('upgrade', function ( res, remoteSocket, head) { + + // + // Prepare handshake response 'headers' and 'statusCode'. + // + reverseProxy.handshake = { + headers: res.headers, + statusCode: res.statusCode, + } + // // Prepare the socket for the reverseProxy request and begin to // stream data between the two sockets. Here it is important to @@ -719,6 +737,28 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, head, buffer) // reverseProxy.once('socket', function (revSocket) { revSocket.on('data', function handshake (data) { + + // Set empty headers + var headers = ''; + + // + // If the handshake statusCode 101, concat headers. + // + if(reverseProxy.handshake.statusCode && reverseProxy.handshake.statusCode == 101){ + + headers = [ + 'HTTP/1.1 101 Switching Protocols' + , 'Upgrade: websocket' + , 'Connection: Upgrade' + , 'Sec-WebSocket-Accept: ' + reverseProxy.handshake.headers['sec-websocket-accept'] + ]; + + headers = headers.concat('', '').join('\r\n'); + + } + + + // // Ok, kind of harmfull part of code. Socket.IO sends a hash // at the end of handshake if protocol === 76, but we need @@ -748,7 +788,8 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, head, buffer) // from the original incoming request. // self.emit('websocket:handshake', req, socket, head, sdata, data); - socket.write(sdata); + // add headers to the socket + socket.write(headers+sdata); var flushed = socket.write(data); if (!flushed) { revSocket.pause();