Add headers on 'handshake'

The headers in the 'handshake' event were not written to the socket, the client received data but not the headers.
This commit is contained in:
Ivan Jaramillo 2013-04-08 11:06:27 -05:00 committed by indexzero
parent 98f5c462ea
commit 985025c90f

View File

@ -698,6 +698,15 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
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
@ -707,7 +716,16 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
// 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
@ -723,6 +741,28 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
//
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
@ -752,7 +792,8 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
// 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();