Alessandro Vendrame
Alessandro Vendrame

Reputation: 300

How can I implement socket.IO with Cloud Functions?

So basically I'm doing a game where the server sends messages to clients, and the client who answer first recieve 1 pnt. I'm trying to create rooms to improve the multiplayer mode, but I'm stuck at this point.

I'm trying to connect socket.io to my google Firebase functions, but when I call the function it returns this error:

Billing account not configured. External network is not accessible and quotas are severely limited. 
Configure billing account to remove these restrictions
10:13:08.239 AM
addStanza
Uncaught exception
10:13:08.242 AM
addStanza
Error: getaddrinfo EAI_AGAIN at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:67:26)
10:13:08.584 AM
addStanza
Error: function crashed out of request scope Function invocation was interrupted.

This is the code:

//firebase deploy --only functions
const Proverbi = require('./Proverbi.js');
const socketIo = require("socket.io");
const https = require("https");
const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp();

var server = https.createServer();
server.listen(443, "https://us-central1-chip-chop.cloudfunctions.net");
var io = socketIo.listen(server);

// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.addStanza = functions.https.onRequest(async (req, res) => {
    // Grab the text parameter.
    const nome = req.query.nome;
    // Push the new message into the Realtime Database using the Firebase Admin SDK.
    const snapshot = await admin.database().ref('/stanze').push({ giocatori: { giocatore: { nome: nome, punteggio: 0 } } });
    // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
    //res.redirect(200, nome.toString());
    var link = snapshot.toString().split('/');
    res.json({ idStanza: link[4] });
});

// Listens for new messages added to /messages/:pushId/original and creates an
//  uppercase version of the message to /messages/:pushId/uppercase

exports.addFirstPlayer = functions.database.ref('/stanze/{pushId}/giocatori/giocatore/nome')
.onCreate((snapshot, context) => {
    // Grab the current value of what was written to the Realtime Database.
    const nome = snapshot.val();
    // const snapshot3 = snapshot.ref('/stanza/{pushId}/giocatori/giocatore').remove();
    const snapshot2 = snapshot.ref.parent.parent.remove();
    var room = snapshot.ref.parent.parent.parent.val();
    // handle incoming connections from clients
    io.sockets.on('connection', function (socket) {
        // once a client has connected, we expect to get a ping from them saying what room they want to join
         socket.on('room', function (room) {
              socket.join(room);
         });
    });
    io.sockets.in(room).emit('message', nome + 'Si è unito alla stanza');
    return snapshot.ref.parent.parent.push({ nome: nome, punteggio: 0, room:room });
});

exports.addPlayer = functions.https.onRequest(async (req, res) => {
     // Grab the text parameter.
     const nome = req.query.nome;
     const idStanza = req.query.id;
     // Push the new message into the Realtime Database using the Firebase Admin SDK.
     const snapshot = await admin.database().ref('/stanze/' + idStanza + "/giocatori").push({ nome: nome, punteggio: 0 });
     // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
     var room = idStanza;
     // handle incoming connections from clients
     io.sockets.on('connection', function (socket) {
              // once a client has connected, we expect to get a ping from them saying what room they want to join
              socket.on('room', function (room) {
                      socket.join(room);
              });
     });
     io.sockets.in(room).emit('message', nome + 'Si è unito alla stanza');
     //res.redirect(200, nome.toString());
     res.json({ success: { id: idStanza } });
});

Is the function crashing only because my firebase plan is limited? Or is there other problems?

Upvotes: 0

Views: 869

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317497

It's not possible to use Cloud Functions as a host for socket-based I/O. Calls to "listen" on any port will fail every time. The provided network infrastructure only handles individual HTTP requests with a request and response payload size of 10MB per request. You have no control over how it handles the request and response at the network level.

Upvotes: 1

Related Questions