gpt4 book ai didi

node.js - 通过 Node 代理服务器运行的基于 Socket.io 的应用程序在断开连接时断开所有套接字

转载 作者:搜寻专家 更新时间:2023-10-31 22:45:31 24 4
gpt4 key购买 nike

我使用 node.jsexpresssocket.io 制作了一个基本的聊天应用程序。它与 tutorial chat app 没有太大区别对于 socket.io,它只是在连接的客户端之间发出事件。当我在服务器的 3001 端口上运行它时,它工作正常。

然后我使用 node-http-proxy 制作了一个代理服务器应用程序它监听端口 80 并根据请求的 url 将流量重定向到我在不同端口上运行的各种独立 Node 应用程序。非常简单。但是有什么东西坏了。每当有人断开连接时,每个套接字都会断开并重新连接。这对我的聊天应用程序不利,它具有基于连接的事件。客户端控制台均显示:

WebSocket connection to 'ws://[some socket info]' failed: Connection closed before receiving a handshake response

以下是我认为代码的重要部分。

代理服务器.js

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

//create proxy template object with websockets enabled
var proxy = httpProxy.createProxyServer({ws: true});

//check the header on request and return the appropriate port to proxy to
function sites (req) {
//webapps get their own dedicated port
if (req == 'mychatwebsite.com') {return 'http://localhost:3001';}
else if (req == 'someothersite.com') {return 'http://localhost:3002';}
//static sites are handled by a vhost server on port 3000
else {return 'http://localhost:3000';}
}

//create node server on port 80 and proxy to ports accordingly
http.createServer(function (req, res) {
proxy.web(req, res, { target: sites(req.headers.host) });
}).listen(80);

聊天应用.js

/*
...other modules
*/
var express = require("express");
var app = exports.app = express(); //I probably don't need "exports.app" anymore
var http = require("http").Server(app);
var io = require("socket.io")(http);

io.on("connection", function (socket) {
/*
...fun socket.on and io.emit stuff
*/
socket.on("disconnect", function () {
//say bye
});
});

http.listen(3001, function () {
console.log("listening on port 3001");
});

现在根据我在 socket.io's site 上阅读的内容,我可能需要使用一些东西来通过我的代理服务器传输套接字流量。我认为 node-http-proxy 使用 {ws: true} 选项为我做了这件事,正如它在 their docs 中所述,但显然它不像我想象的那样工作。 socket.io 提到了三个不同的东西:

我完全不知道这意味着什么或做什么。我不小心在这里编写了超出我技能水平的代码,我不知道这些工具中的哪一个可以解决我的问题(如果有的话),甚至我的问题的真正原因是什么。

必须道歉:我是 node.js 的新手,所以请原谅我。

也是强制性的:我知道像 nginx 这样的其他应用程序可以解决我的很多问题,但我的目标是在开始使用新工具之前学习和理解如何使用这套工具。而且,我使用的应用程序越少越好。

最佳答案

我认为您关于需要“通过代理服务器传送套接字流量”的直觉是正确的。要建立 websocket,客户端会发出带有特殊 Upgrade header 的 HTTP 请求,向服务器发出信号以切换协议(protocol) (RFC 6455)。在 Node 中,http.Server 实例会在发生这种情况时发出一个 upgrade 事件,如果未处理该事件,连接将立即关闭。

您需要在您的 http 服务器上监听 upgrade 事件并处理它:

var proxy = httpProxy.createProxyServer({ws: true})
var http = http.createServer(/* snip */).listen(80)

// handle upgrade events by proxying websockets
// something like this
http.on('upgrade', function (req, socket, head) {
proxy.ws(req, socket, head, {target:sites(req.headers.host)})
})

参见 node docs on the upgrade eventnode-http-proxy docs了解更多。

关于node.js - 通过 Node 代理服务器运行的基于 Socket.io 的应用程序在断开连接时断开所有套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28629073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com