javascript - 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 代码不是这里的问题。我上面显示的服务器代码一定有问题。
解决方案
由于您没有提供完整的源代码,我只能假设可能出了什么问题。
首先,由于您使用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 关键字,它只是箭头函数的一部分)
推荐阅读
- python - 如何与前一组(月)的同一行执行自连接以在 Pyspark 中引入其他列
- javascript - 直接使用变量名与 getElementById 引用元素
- python - 有人知道如何为 anaconda/spyder 安装 gtk3 吗?在窗户上
- next.js - VIDEOJS:错误:(代码:4 MEDIA_ERR_SRC_NOT_SUPPORTED)与 Azure 媒体服务
- flutter - 如何在 Flutter 中使用 CustomPainter 绘制动画帧?
- javascript - firestore valueChanges() 不会立即更新用户数据
- dask - 从 Minio 读取 Dask 引发了将二进制字符串 JSON 读取/转换为 utf8 的问题
- xquery - 换行在 XQuery 的行尾留下额外的空间
- vue.js - 如何在 vue.config.js 中使用 ES6?
- javascript - 生成新颜色而不刷新页面