如何将socket.io附加到google firebase app功能?

时间:2017-04-15 23:08:57

标签: firebase socket.io

我在index.js文件中有以下代码,位于google firebase proyect的functions文件夹中:

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.,当我转到网址http://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)=>{res.send("Firebase working!")})时,问题就出现了,这似乎是不可能的。

1 个答案:

答案 0 :(得分:8)

您无法使用云功能运行代码来侦听某个端口。这是因为您无法保证运行代码的单个计算机或实例。它可以分布在所有并发运行的实例中。如果发生这种情况,您不应该知道或关心 - 云功能只会扩展以满足您对功能的需求。

如果部署HTTP类型功能,它将自动侦听https端口以获取项目的专用主机,并且可以向其发送Web请求。

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