【问题标题】:How to attach socket.io to google firebase app functions?如何将 socket.io 附加到 google firebase 应用程序功能?
【发布时间】:2017-04-15 23:08:56
【问题描述】:

我在我的 google firebase proyect 的函数文件夹中的 index.js 文件中有以下代码:

net=require('express')()
net.get('/',function(req,res){res.sendFile(__dirname+'/slave.htm')})
exports.run=require('firebase-functions').https.onRequest(net)
require('socket.io').listen(net).on("connection",function(socket){})

但是当我在命令提示符下执行\gfp1>firebase deploy 时,这给了我错误:

您正在尝试将 socket.io 附加到一个快速请求处理函数。请传递一个 http.Server 实例。

是的,我在下面的代码中传递了http服务器实例:

net=require('firebase-functions').https.onRequest((req,res)=>{res.send("socket.io working!")})
exports.run=net;require('socket.io').listen(net).on("connection",function(socket){})

它再次给了我以下错误:

您正在尝试将 socket.io 附加到一个快速请求处理函数。请传递一个 http.Server 实例。

我尝试使用该代码将 socket.io 附加到 firebase 函数:

net=https.onRequest((req,res)=>{res.send("socket.io working!")})
exports.run=require('firebase-functions').net
require('socket.io').listen(require('firebase-functions').net).on("connection",function(socket){})

这给出了这个错误:

https 没有定义

当我在 localhost 中运行此代码时:

app=require('express')()
app.get('/',function(req,res){res.sendFile(__dirname+'/slave.htm')})
net=require('http').createServer(app);net.listen(8888,function(){console.log("Server listening.")})
require('socket.io').listen(net).on("connection",function(socket){})

控制台发出\gfp>Server listening.,当我转到urlhttp://127.0.0.1:8888时,它可以向导航器发送一个html文件,正如我所料:

<script>
document.write("File system working!")
document.body.style.backgroundColor="black"
document.body.style.color="white"
</script>

但是当我尝试将net=require('http').createServer(app);net.listen(8888,function(){console.log("Server listening.")})转换为net=exports.run=require('firebase-functions').https.onRequest((req,res)=&gt;{res.send("Firebase working!")})时出现问题,这似乎是不可能的。

【问题讨论】:

    标签: firebase socket.io


    【解决方案1】:

    您无法使用 Cloud Functions 运行代码来侦听某些端口。这是因为不能保证您有一台机器或实例运行您的代码。它可以分布在所有同时运行的许多实例中。您不应该知道或关心是否会发生这种情况 - Cloud Functions 只会扩展以满足您对函数的需求。

    如果你部署一个 HTTP 类型的函数,它会自动监听你项目的专用主机的 https 端口,你可以向它发送网络请求。

    如果您想通过永久持有的套接字执行事务,请使用实时数据库客户端在数据库中写入值,然后使用您编写的数据库触发器函数响应这些写入。该函数可以通过将某些内容写回到客户端正在侦听的位置的数据库中,将数据发送回客户端。

    【讨论】:

    • 抱歉,我应该写一个新问题,想知道如何使用实时数据库吗?
    • 您可能需要阅读文档并尝试自己先实现一些东西。 Stack Overflow 不适合提出广泛的开放式问题。
    • @DougStevenson ,我认为这个答案在 2020 年第一季度变得更加相关。由于 GPGS 正在关闭,每个人都在洗牌以解决实时多人游戏。现在这是新蜜蜂感到困惑的地方。 SocketIO 非常适合,他们希望通过 Firebase Hosting 运行它。但 Firebase RealTime Db 的表现如此出色,以至于他们实际上将其误认为是 Realtime MultiPlayer 数据传输工具! ;-).... 我真的觉得 Firebase 应该比 2017 年的 David 教程更新并更好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-09-11
    • 2014-06-18
    • 2020-11-10
    • 2011-04-13
    • 2010-12-13
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多