【问题标题】:Websockets not working on Google App EngineWebsockets 无法在 Google App Engine 上运行
【发布时间】:2020-01-07 21:38:36
【问题描述】:

我最近向 Google App Engine 部署了一个 node.js 服务器应用程序,该应用程序通过 socket.io 与客户端应用程序通信。根据this article,App Engine 现在支持 websocket。

但是,客户端应用程序无法通过 wss 协议连接到服务器。我可以在浏览器控制台中看到以下错误消息。 (我删除了我的服务器域)

与“wss://[my server]/socket.io/?EIO=3&transport=websocket&sid=dbB2UgsCYhD7c1ucAAAA”的 WebSocket 连接失败:WebSocket 握手期间出错:意外响应代码:400

Socket.io 然后回退到 https 长轮询,效果很好。

这是我的 app.yaml 用于部署到应用引擎,session_affinity 设置为 true 以进行长轮询。

runtime: nodejs10

instance_class: F2

handlers:
- url: /.*
  secure: always
  redirect_http_response_code: 301
  script: auto

network:
  session_affinity: true

Socket.io 直接用在服务器端:

this.server = this.app.listen(this.PORT, (err: any) => {
  io = socketio().listen(this.server);
  io.on("connection", (socket) => {
    console.log('A socket connection was made!');
  });
});

我想知道如何让 websocket 连接在 App Engine 上工作?也许需要防火墙规则或其他配置更改?

【问题讨论】:

    标签: node.js google-app-engine websocket socket.io


    【解决方案1】:
    var express = require('express');
    var app = express();
    var expressWs = require('express-ws')(app);
    
    const forceSecure = (req, res, next) => {
      if (req.secure)
         return next(); // https -- Continue
    
      res.redirect('https://' + req.hostname + req.url)
    }
    
    /**
    * This will force
    * ALL HTTP requests ( GET, POST, OPTIONS, etc. )
    * on ALL route handlers to be
    * redirected to https 
    */
    app.all('*', forceSecure);
    
    app.get('/', (req, res, next) => {
      console.log('example');
      res.end();
    });
    
    app.ws('/', (ws, req) => {
      ws.on('message', msg => {
        console.log(msg);
      });
      console.log('socket', req.example);
    });
    
    app.listen(3000);
    

    到目前为止,WebSockets 是only supported in the Flexible Environment for App Engine。据我所知,您正在标准环境中部署应用程序,如您指定的instance_class 所示:instance_class: F2。因此,我建议将环境从 Standard 更改为 Flexible,请参阅 here 了解 Flex 中的 app.yaml 配置文件。这样做可以让您利用最近在 App Engine 中实现的 WebSockets 功能。

    【讨论】:

    • 感谢您的信息。你知道吗,如果我切换到柔性环境,我还可以使用 app.yaml 中的 handlers 部分吗? flex 文档没有列出该部分:cloud.google.com/appengine/docs/flexible/nodejs/reference/…
    • 您好,很遗憾,handlers 只能在 App Engine 标准中使用。但是,您可以通过代码创建路由处理程序。就个人而言,我过去曾使用过 express-ws,如果您有任何编写 express.js 应用程序的经验,可以让您编写 WebSocket 端点,类似于编写任何其他路由处理程序的方式。
    • 再次感谢。我想我对处理程序的唯一关心是如何在 flex 环境中将流量从 http 重定向到 https。
    • 不用担心,也可以通过代码强制使用https。假设使用了express-ws,您可以创建一个中间件,它将所有不安全的流量重定向到 https 并将其附加到所有 http 方法的所有路由处理程序。我相应地编辑了我的答案,以便向您说明这是如何工作的。
    猜你喜欢
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 2012-11-28
    相关资源
    最近更新 更多