Google 云 socket.io 服务器,客户端未保持持久连接

Google Cloud socket.io server, client not keeping persistent connection

我有一个 Node.js 服务器使用 socket.io 连接 Android 应用程序,我一直在本地托管它 运行 它在我的 IDE 并连接到我的本地 IPv4 地址,但我希望它能够工作而不必一直保持我的 PC 运行 所以我尝试使用 Google Cloud 并设法让它大部分工作但客户端没有'始终保持连接和断开连接。

我按照 this tutorial 进行到第 4 步,然后 运行 gcloud app deploy。

我的 Node.js 服务器在一个文件中,它在顶部有这些声明。

const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

然后我将其用于初始客户端连接。

io.on("connection", (socket) => {
    console.log("User connected.");

其中的所有内容都只是监听客户端发出的内容,所以我认为它们不是问题所在。

除此之外我还有

server.listen(8080, () => {
    console.log("Server is listening");
});

我不知道 package.json 文件中的任何内容是否相关,但如果需要我可以提供。

使用 tutorial 部署到 Google 云后,日志中的一些内容可能是问题背后的原因。

Waiting for network connection open. Subject:"app/invalid" Address:127.0.0.1:8080

Waiting for network connection open. Subject:"app/invalid" Address:127.0.0.1:8081

Wait successful. Subject:"app/invalid" Address:127.0.0.1:8080 Attempts:97 Elapsed:485.916418ms

App is listening on port 8080. We recommend your app listen on the port defined by the PORT environment variable to take advantage of an NGINX layer on port 8080.

这些可能有简单的解决方案,但我对服务器托管的经验很少。

一旦我的 Android 客户端连接到服务器,日志就会输出“用户已连接”。正如它应该的那样,然后大约 10 秒后它再次执行并重复此操作。我可以在连接之间看到没有错误,只有几个 socket.io POST/GET 请求。

我尝试将会话关联添加到 app.yaml,但也没有解决。

这是我的app.yaml如果这里需要修改

runtime: nodejs16
env: standard
instance_class: F1
automatic_scaling:
  min_idle_instances: automatic
  max_idle_instances: automatic
  min_pending_latency: automatic
  max_pending_latency: automatic
network:
  session_affinity: true

感谢您的帮助,如果我需要提供任何其他文件,我可以这样做。

您粘贴的消息很可能没有问题。您的应用程序 运行 处于沙盒环境中,在您的应用引擎服务第一次收到请求时,必须初始化容器实例和网络服务器。这也称为 Loading request,您看到的消息表明您的容器实例和网络服务器已启动。
可以看看Google自己的documentation regarding handling requests in node.js or follow a quickstart guide.
如果在断开连接期间没有其他日志,我建议检查 quotas 看看你是否没有超过任何。

套接字通信需要持续的网络连接。因此,App Engine Flexible 提供了一个选项来保持网络连接有效。 我认为您正在 App Engine Standard 中部署您的应用程序,它不支持此选项。 因此,您可以在 App Engine Flexible 中部署您的应用程序,并且您需要在 app.yaml

中包含以下配置
network:
    session_affinity: true

有关会话亲和性的参考,请参阅此页面https://cloud.google.com/appengine/docs/flexible/nodejs/using-websockets-and-session-affinity#session_affinity 因此,您更新后的 app.yaml 可能如下所示

runtime: nodejs
env: flex
network:
  session_affinity: true

有关灵活环境支持的 yaml 配置,请参阅此页面 - https://cloud.google.com/appengine/docs/flexible/nodejs/reference/app-yaml