15

我有一个通过 socket.io 使用 websockets 的应用程序。对于我的应用程序,我想使用单独的 HTTP 服务器来为我的应用程序提供静态内容和 JavaScript。因此,我需要放置一个代理。

我正在使用node-http-proxy。作为起点,我的 websockets 应用程序在端口 8081 上运行。我使用以下代码将 socket.io 通信重定向到这个独立服务器,同时使用 express 提供静态内容:

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

// create a server
var app = express();
var proxy = httpProxy.createProxyServer({ ws: true });

// proxy HTTP GET / POST
app.get('/socket.io/*', function(req, res) {
  console.log("proxying GET request", req.url);
  proxy.web(req, res, { target: 'http://localhost:8081'});
});
app.post('/socket.io/*', function(req, res) {
  console.log("proxying POST request", req.url);
  proxy.web(req, res, { target: 'http://localhost:8081'});
});

// Proxy websockets
app.on('upgrade', function (req, socket, head) {
  console.log("proxying upgrade request", req.url);
  proxy.ws(req, socket, head);
});

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

app.listen(8080);

上面的应用程序工作得很好,但是,我可以看到 socket.io 不再使用 websockets,而是回退到 XHR 轮询。

我可以通过查看代理代码中的日志来确认:

proxying GET request /socket.io/1/?t=1391781619101
proxying GET request /socket.io/1/xhr-polling/f-VVzPcV-7_IKJJtl6VN?t=13917816294
proxying POST request /socket.io/1/xhr-polling/f-VVzPcV-7_IKJJtl6VN?t=1391781629
proxying GET request /socket.io/1/xhr-polling/f-VVzPcV-7_IKJJtl6VN?t=13917816294
proxying GET request /socket.io/1/xhr-polling/f-VVzPcV-7_IKJJtl6VN?t=13917816294

有谁知道如何代理网络套接字通信?来自的所有示例node-http-proxy都假设您要代理所有流量,而不是代理一些流量并为其他流量提供服务。

4

2 回答 2

21

刚刚偶然发现你的问题,我看到它仍然没有回答。好吧,如果您仍在寻找解决方案...您的代码中的问题是这app.listen(8080)只是语法糖

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

app它本身只是一个处理函数,而不是 httpServer 的一个实例(我个人认为应该从 Express 中移除这个特性以避免混淆)。因此,您app.on('upgrade')实际上从未使用过。你应该改为写

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

希望,这有帮助。

于 2014-03-24T09:14:35.047 回答
1

你需要两台服务器吗?如果不是,您可以将同一台服务器用于静态文件并侦听套接字连接:

// 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
于 2014-02-07T16:19:23.877 回答