Websockets 不适用于 Google App Engine

woo*_*ers 5 google-app-engine websocket node.js socket.io

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

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

WebSocket 连接到“wss://[我的服务器]/socket.io/?EIO=3&transport=websocket&sid=dbB2UgsCYhD7c1ucAAAA”失败: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
Run Code Online (Sandbox Code Playgroud)

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!');
  });
});
Run Code Online (Sandbox Code Playgroud)

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

JKl*_*nne 8

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);
Run Code Online (Sandbox Code Playgroud)

截至目前,WebSockets仅在 App Engine 的灵活环境中受支持。从我所看到的,要部署在标准环境下的应用程序,由所表示instance_class您指定:instance_class: F2。因此,我建议将环境从标准更改为灵活,请参阅此处了解 Flex 中的 app.yaml 配置文件。这样做可以让您利用最近在 App Engine 中实现的 WebSockets 功能。