我正在尝试利用带有防火墙托管/函数的socket.io连接,但我遇到了一些问题。它最初是CORS问题(我确定这仍然是问题所在),但现在我完全不知道出了什么问题,下面是我的firebase.json、index.js (firebase函数文件),甚至初始化到服务器连接的角客户端文件。
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;
}
}这就是我要犯的错误。

我在堆栈溢出和其他有类似问题的网站上看了几篇文章,但似乎都没有效果。我肯定我做错了,但我迷失了我所缺少的去完成这件事。请帮帮我!
发布于 2020-01-16 14:28:56
云功能是用于相对较短的操作,有一个明确的目的。不能使用云函数保持与客户端的连接打开。
原因是,当云函数认为您已经完成任务时,它会关闭容器的资源。对于像您这样的HTTP函数,这意味着当您调用response.send('Hello!');时,这些资源就消失了。
因此,一旦您建立了这样的套接字连接,就可以将响应发送到客户机:
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分钟后关闭,因为这是云函数运行的最大时间。
这一切都可以追溯到我最初的声明,即云函数只适用于短暂的操作,并且有明确的结束时刻。对于长期运行的流程,请使用另一个平台,如App、Compute或许多其他产品中的一个,您可以在其中管理自己的流程。
另请参阅:
https://stackoverflow.com/questions/59769019
复制相似问题