【发布时间】:2020-05-02 23:15:18
【问题描述】:
我正在尝试使用 ReactJS、NodeJS 和 Socket.IO 制作类似于多人游戏大厅的东西。每次新的播放器/客户端连接到套接字时,我都希望在前端广播他们的名字。
到目前为止,我已经能够通过让前端每 3 秒向后端发出一次 GET 请求来实现这一点,这会触发后端上的套接字以发送从 mongoDB 数据库获取的数据。
前端 - lobby.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 秒定期检查一次,无论是否有更改数据与否?
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: node.js reactjs mongodb sockets socket.io