http-party / node-http-proxy

A full-featured http proxy for node.js
https://github.com/http-party/node-http-proxy
Other
13.88k stars 1.97k forks source link

want HTTP proxy and WebSocket both working #688

Open ericq opened 10 years ago

ericq commented 10 years ago

I want a HTTP proxy and WebSocket proxy to support a deployd backend. I always received this error Msg from the browser side. WebSocket connection to 'ws://localhost:8000/socket.io/1/websocket/Bw-GcrkRQecfNjOue7xi' failed: Connection closed before receiving a handshake response

This is my code. I'm very new to this. So please help me.

var http = require('http'), httpProxy = require('http-proxy');

// // Create a proxy server with custom application logic // var proxy = httpProxy.createProxyServer({}); var defaultTarget = 'http://127.0.0.1:9000'; // this 9000 serves my AngularJs Client

var getTarget = function (req) { console.log('req.url='+req.url); if (req.url.match(/node/)) { req.url = req.url.replace(/node\/api\//, ''); console.log('updaded to='+req.url); return 'http://localhost:2403'; // this 2403 is for deployd REST API } else if (req.url.match(/socket.io\//)) { console.log('visiting '+req.url); if (req.protocol == 'http') { return 'http://localhost:2403'; // for deployd SocketIO? } else { return 'ws://localhost:2403'; } } else if (req.url.match(/auth/)) { console.log('visiting '+req.url); return 'http://localhost:3000'; }

else return defaultTarget; }

// var server = require('http').createServer(function(req, res) { proxy.web(req, res, { target: getTarget(req) }); });

console.log("listening on port 8000")

bjackson commented 9 years ago

Socket.io's handshake requires the HTTP upgrade request and the websocket server to be on the same server. The handshake never completes because it will connect to another server (websocket server on port 2403) that doesn't share the same state as the plain ol' http server on port 3000. You can get around this by using socket.io-redis.