[英]Socket.io - Client listens to data changes from server automatically
我正在尝试使用 ReactJS、NodeJS 和 Socket.IO 制作类似于多人游戏大厅的东西。 每次新的播放器/客户端连接到套接字时,我都希望在前端广播他们的名字。
到目前为止,我已经能够通过让前端每 3 秒向后端发出一次 GET 请求来实现这一点,这会触发后端的套接字发送从 mongoDB 数据库获取的数据。
前端 - 大厅.js
class Lobby extends Component {
//When the component mounts, it calls grabNames function every 3 seconds.
componentDidMount = () => {
setInterval(this.grabNames, 3000);
};
//function makes a GET request that triggers the socket to emit a "joinedPlayers" message.
grabNames = () => {
axios.get(`${backend}/playerNames`).then(response => {
console.log("Success");
});
//Listens for the "joinedPlayers" message to be emitted from the backend.
//The joinedPlayers state is then referenced in the client-side markup.
socket.on("joinedPlayers", data => {
this.setState({ joinedPlayers: data.map(name => <li>{name}</li>) });
});
};
后端 - server.js
//Function for connecting to the mongoDB database through Mongoose.
function dbConnect() {
mongoose
.connect(database, { useNewUrlParser: true })
.catch(error => console.error(error));
}
//Socket Connection
io.on("connection", socket => {
console.log("A connection to the socket has been established.");
});
//Router
app.get("/playerNames", (req, res) => {
dbConnect();
Name.find((error, array) => {
var playerNames = array.map(name => name.name);
io.emit("joinedPlayers", playerNames);
res.send("Player names emitted.");
});
});
虽然这种方法对我有用,但我不禁认为前端有更好的方法来侦听来自服务器的数据更改。
例如,有没有办法服务器可以检测到我的 mongoDB 数据库中的更改并仅在检测到此更改时更新客户端……而不必每 3 秒定期检查一次,无论数据是否发生更改或不是?
任何帮助将不胜感激。 谢谢!
最好为每个游戏创建房间/频道并将所有玩家连接到该房间(从客户端),而不是发出 GET 请求。 现在,当新玩家订阅该房间时,(将触发一个事件)。 您可以为频道广播事件。
像下面这样:
io.on('connection', function(socket){
socket.on('joinedPlayers', function(id, msg){
socket.broadcast.to('game id').emit('Jamie joined', msg);
});
});
查看更多信息: https : //socket.io/docs/rooms-and-namespaces/#Default-room
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.