Как я могу реализовать socket.IO с помощью облачных функций? - PullRequest
0 голосов
/ 07 мая 2020

Итак, в основном я делаю игру, в которой сервер отправляет сообщения клиентам, а клиент, который отвечает первым, получает 1 pnt. Я пытаюсь создать комнаты, чтобы улучшить многопользовательский режим, но на этом застрял.

Я пытаюсь подключить socket.io к моим функциям Google Firebase, но когда я вызываю функцию, возвращает эту ошибку:

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.

Это код:

//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 } });
});

Функция дает сбой только из-за того, что мой план firebase ограничен? Или есть другие проблемы?

1 Ответ

0 голосов
/ 07 мая 2020

Невозможно использовать облачные функции в качестве хоста для ввода-вывода на основе сокетов. Вызовы "прослушивания" на любом порту будут терпеть неудачу каждый раз. Предоставляемая сетевая инфраструктура обрабатывает только отдельные HTTP-запросы с размером полезной нагрузки запроса и ответа 10 МБ на запрос. Вы не можете контролировать, как он обрабатывает запрос и ответ на сетевом уровне.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...