首页 > 解决方案 > Socket IO Rooms:尝试在游戏应用程序中使用房间(react-native),以便多组人可以相互独立地玩游戏

问题描述

我有一个应用程序,多人通过输入在托管游戏的手机上生成的代码来加入游戏。我想将此代码用作套接字 io 房间的名称,因此可以在不同的玩家组之间进行多个游戏。

这是我的服务器代码:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(3000);

io.on('connection', function (socket) {
    //passing in the game_code from client side and using it as the room name
    socket.on('names', function (game_code) {
        socket.join(game_code);
        io.to(game_code).emit('names')
    });
    socket.on('round_start', function (game_code) {
        io.to(game_code).emit('round_start')
    });
    socket.on('game_start', function (game_code) {
        io.to(game_code).emit('game_start')
    });
    socket.on('end_round', function (game_code) {
        io.to(game_code).emit('end_round')
    });
    socket.on('next_round', function (game_code) {
        io.to(game_code).emit('next_round')
    });
    socket.on('end_game', function (game_code) {
        io.to(game_code).emit('end_game')
    });
});

'names' 插槽用于玩家在游戏开始前输入他们的名字,其余的用于过渡到下一个屏幕;一部电话,通常是主机,按下一个按钮,使所有电话进入下一个屏幕。'names' 套接字工作正常,'round_start' 套接字也是如此,这是第一个屏幕转换。此后的下一个屏幕转换不起作用。

如果我不使用房间,所有的屏幕转换都可以工作,所以我很确定我的 react-native 代码不是这里的问题。我上面显示的服务器代码一定有问题。

标签: javascriptreact-nativesocket.io

解决方案


由于您没有提供完整的源代码,我只能假设可能出了什么问题。

首先,由于您使用io.to(game_code).emit('names')了我假设,您希望将 'names' 事件发送给房间中的所有客户端game_code,包括发送者。

(旁注:如果您希望将此事件发送给房间中的所有用户,除了发送者,您应该使用socket.to(game_code).emit('names'). 请参阅https://socket.io/docs/emit-cheatsheet/

但是,由于该.join方法是异步的,“names”事件可能会在客户端加入房间之前被触发。所以发送者永远不会收到他自己触发的'names'事件,只有其他客户端触发的'names'事件。

为确保在客户端加入房间后触发 'names' 事件,您可以对.join方法使用回调: socket.join(room, callback).

io.on('connection', function (socket) {
  //passing in the game_code from client side and using it as the room name
  socket.on('names', function (game_code) {
      socket.join(game_code, (game_code) => io.to(game_code).emit('names'););
  });
  //rest of your code
});

如果您不熟悉=>箭头功能,(game_code) => io.to(game_code).emit('names')则为

function (game_code){
  return io.to(game_code).emit('names');
}

(没关系 return 关键字,它只是箭头函数的一部分)


推荐阅读