套接字IO室:试图在游戏应用程序中使用房间(本地反应),这样多组人可以独立玩游戏

问题描述 投票:0回答:1

我有一个应用程序,通过输入在托管游戏的手机上生成的代码,多人加入游戏。我想使用此代码作为套接字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'套接字也是如此,这是第一个屏幕转换。此后的下一个屏幕转换不起作用。

如果我不使用房间,所有屏幕转换都有效,所以我很确定我的反应本机代码不是问题。我上面显示的服务器代码一定有问题。

javascript react-native socket.io
1个回答
0
投票

既然你没有提供完整的资源,我只能假设可能出现的问题。

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

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

但是,由于.join方法是异步的,因此在客户端加入房间之前,'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关键字,它只是箭头功能的一部分)

© www.soinside.com 2019 - 2024. All rights reserved.