@@ -698,6 +698,15 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
698
698
socket : socket ,
699
699
head : head
700
700
} ;
701
+
702
+ //
703
+ // Here we set the handshake `headers` and `statusCode` data to the outgoing
704
+ // request so that we can reuse this data later.
705
+ //
706
+ reverseProxy . handshake = {
707
+ headers : { } ,
708
+ statusCode : null ,
709
+ }
701
710
702
711
//
703
712
// If the agent for this particular `host` and `port` combination
@@ -707,7 +716,16 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
707
716
// In addition, it's important to note the closure scope here. Since
708
717
// there is no mapping of the socket to the request bound to it.
709
718
//
710
- reverseProxy . on ( 'upgrade' , function ( _ , remoteSocket , head ) {
719
+ reverseProxy . on ( 'upgrade' , function ( res , remoteSocket , head ) {
720
+
721
+ //
722
+ // Prepare handshake response 'headers' and 'statusCode'.
723
+ //
724
+ reverseProxy . handshake = {
725
+ headers : res . headers ,
726
+ statusCode : res . statusCode ,
727
+ }
728
+
711
729
//
712
730
// Prepare the socket for the reverseProxy request and begin to
713
731
// stream data between the two sockets. Here it is important to
@@ -723,6 +741,28 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
723
741
//
724
742
reverseProxy . once ( 'socket' , function ( revSocket ) {
725
743
revSocket . on ( 'data' , function handshake ( data ) {
744
+
745
+ // Set empty headers
746
+ var headers = '' ;
747
+
748
+ //
749
+ // If the handshake statusCode 101, concat headers.
750
+ //
751
+ if ( reverseProxy . handshake . statusCode && reverseProxy . handshake . statusCode == 101 ) {
752
+
753
+ headers = [
754
+ 'HTTP/1.1 101 Switching Protocols'
755
+ , 'Upgrade: websocket'
756
+ , 'Connection: Upgrade'
757
+ , 'Sec-WebSocket-Accept: ' + reverseProxy . handshake . headers [ 'sec-websocket-accept' ]
758
+ ] ;
759
+
760
+ headers = headers . concat ( '' , '' ) . join ( '\r\n' ) ;
761
+
762
+ }
763
+
764
+
765
+
726
766
//
727
767
// Ok, kind of harmfull part of code. Socket.IO sends a hash
728
768
// at the end of handshake if protocol === 76, but we need
@@ -752,7 +792,8 @@ HttpProxy.prototype.proxyWebSocketRequest = function (req, socket, upgradeHead,
752
792
// from the original incoming request.
753
793
//
754
794
self . emit ( 'websocket:handshake' , req , socket , head , sdata , data ) ;
755
- socket . write ( sdata ) ;
795
+ // add headers to the socket
796
+ socket . write ( headers + sdata ) ;
756
797
var flushed = socket . write ( data ) ;
757
798
if ( ! flushed ) {
758
799
revSocket . pause ( ) ;
0 commit comments