2

I'm trying to make an HTTP proxy server using node-http-proxy module but I also want to support WebSocket in my proxy server. For that, I have registered an event listener on the upgrade method like following code which is working perfectly if I pass my local proxy server's URL to agent key of WebSocket

httpServer.on("upgrade", function(req, sock, head) {
    console.log("upgrade called")

    let reqUrl = req.url
    let hostPath = reqUrl.split("//")[1]
    let wsUrl = `ws://${hostPath}`

    proxy.ws(req,sock,head, {
            target: wsUrl,
            ws: true,
            autoRewrite: true,
            changeOrigin: true
    })
})

But when I use my local proxyServer's URL in google-chrome as HTTP proxy URL and then try to use any WebSocket code then it does not call upgrade method of my proxy, instead, chrome calls connect method. So I also listen on the connect method of my HTTP server and wrote the same code with little modification in connect method's callback. You can see my code below

httpServer.on("connect", (req, clientSocket, head) => {
    console.log("connect called")

    let reqUrl = req.url
    let wsUrl = `ws://${reqUrl}`

    proxy.ws(req,clientSocket,head,
        {
            target: wsUrl,
            ws: true,
            autoRewrite: true,
            changeOrigin: true
        })
})

But still, my proxy doesn't work for WebSockets. If I try running var ws=new WebSocket('ws://echo.websocket.org/'); in browser console then I get the following error WebSocket connection to 'ws://echo.websocket.org/' failed: Error in connection establishment: net::ERR_EMPTY_RESPONSE This time connect method was called with no error on the server side but client's WebSocket is not connected

So I want to know, how do I handle the connect method to allow WebSocket connection through my proxy

Point Networks
  • 1,071
  • 1
  • 13
  • 35

0 Answers0