使用 firebase 函数和 express 连接到 socket.io 的问题 [英] Problems connecting to socket.io using firebase functions and express

查看:13
本文介绍了使用 firebase 函数和 express 连接到 socket.io 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有 firebase 托管/功能的 socket.io 连接,但遇到了一些问题.它开始是一个 CORS 问题(我确定这仍然是问题),但现在我完全迷失了,下面是我的 firebase.json、index.js(firebase 函数文件),甚至是 angular 客户端文件初始化与服务器的连接.

I'm trying to utilize a socket.io connection with firebase hosting/functions but I'm running into a few problems. It started off as a CORS issue (which im sure is still the problem) but now I'm just totally lost on whats wrong, below is my firebase.json, index.js (firebase function file), and even the angular client file which initializes the connection to the server.

firebase.json

{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "headers": [ 

      {
        "source" : "**",
        "headers" : [ {
          "key" : "Access-Control-Allow-Headers",
          "value" : "Origin"
        } ]
      },
      {
        "source" : "**",
        "headers" : [ {
          "key" : "Access-Control-Allow-Origin",
          "value" : "http://localhost:4200"
        } ]
      }
    ],
    "rewrites": [
      {
        "source": "**",
        "function": "app"
      }
    ]
  },
  "functions": {
    "predeploy": [
      "npm --prefix "$RESOURCE_DIR" run lint"
    ],
    "source": "functions"
  }
}

index.js

const functions = require('firebase-functions');
const express = require('express');
var app = express();

const http = require('http').Server(express);
const socketio = require('socket.io')(http);
const cors = require('cors');


app.use(cors({credentials: true, origin: '*:*'}));
app.get('/tester', (request, response) => {

    //response.header('Access-Control-Allow-Origin', '*');
    response.send('Hello!');

    socketio.on('connection', socket => {
        connections.push(socket);
        console.log('New client connected ('+connections.length+' connections).');
        //console.log(socket);
        socket.emit('port', 'LIVE SHIT');
    });
})

exports.app = functions.https.onRequest(app)

app.component.ts(用于连接的客户端组件)

import { Component } from '@angular/core';
import io from 'socket.io-client';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'multi-client';
  port: number = 0;
  socket: any;
  width: number = 100;
  updateVal: number = 5;
  constructor()
  {
    this.socket = io('http://localhost:5000/tester');

    this.socket.on('port', port => {
      this.port = port;
    })
  }

  updateWidth(val)
  {
    this.width += val;
  }
}

这是我遇到的错误.

我在 stackoverflow 和其他各种网站上查看了一些帖子,这些帖子有类似的问题,但似乎没有任何效果.我确定我做错了,但我迷失了实现这一目标所缺少的东西.请帮忙!

I viewed a few posts on stackoverflow and various other sites that had similar problems but nothing seemed to work. I'm sure im doing it wrong but I'm lost on what I'm missing to accomplish this. Please help!

推荐答案

Cloud Functions 是针对相对短命且有明确目的的操作.您不能使用 Cloud Functions 保持与客户端的连接打开.

Cloud Functions are for relatively short-lived operations with a clear end. You cannot use Cloud Functions to keep a connection to the client open.

原因是 Cloud Functions 会在它认为您完成时关闭容器的资源.对于像你这样的 HTTP 函数,这意味着当你调用 response.send('Hello!'); 时这些资源就消失了.

The reason is that Cloud Functions closes the resources of your container by the time it thinks you're done. In the case of a HTTP function like yours, that means that these resources are gone when you've called response.send('Hello!');.

所以可能的是,一旦您建立了这样的套接字连接,就可以将响应发送到客户端:

So what is possible is to send the response to the client once you've established a socket connection like this:

app.get('/tester', (request, response) => {


    socketio.on('connection', socket => {
        connections.push(socket);
        console.log('New client connected ('+connections.length+' connections).');
        //console.log(socket);
        socket.emit('port', 'LIVE SHIT');

        response.send('Hello!');
    });
})

但在这种情况下,连接也会在调用 response.send('Hello!'); 后关闭.虽然您可以发送响应,但即使在这种情况下,连接/资源也会在 9 分钟后关闭,因为这是云函数可以运行的最长时间.

But in that case too, the connection will be closed after the call to response.send('Hello!');. And while you could not send a response, even in that case the connection/resources will be closed after 9 minutes, since that is the maximum time a Cloud Function can run.

这一切都可以追溯到我最初的声明,即 Cloud Functions 仅适用于具有明确结束时刻的短期操作.对于长时间运行的流程,请使用其他平台,例如 App Engine、Compute Engine 或您可以管理自己的流程的众多其他产品之一.

It all goes back to my initial statement that Cloud Functions are only for short-lived operations with a clear end moment. For long-running processes, use another platform, such as App Engine, Compute Engine, or one of the many other offerings where you can manage your own processes.

另见:

这篇关于使用 firebase 函数和 express 连接到 socket.io 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆