Using node http-proxy to proxy websocket connections

有些话、适合烂在心里 提交于 2019-12-02 20:49:41

Just stumbled upon your question, and I see that it is still not answered. Well, in case you are still looking for the solution... The problem in your code is that app.listen(8080) is just syntactic sugar for

require('http').createServer(app).listen(8080)

while app itself is just a handler function, not an instance of httpServer (I personally believe that this feature should be removed from Express to avoid confusion). Thus, your app.on('upgrade') is actually never used. You should instead write

var server = require('http').createServer(app);
server.on('upgrade', function (req, socket, head) {
  proxy.ws(req, socket, head);
});
server.listen(8080);

Hope, that helps.

Do you need both servers? If not you could use the same server for static files and to listen for socket connections:

// make the http server
var express = require('express'),
    app = express(), server = require('http').createServer(app),
    io;

// serve static content
server.use('/', express.static(__dirname + '/public'));

server.listen(8080);

// listen for socket connections
io = require('socket.io').listen(server);

// socket stuff here
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!