【问题标题】:Socket.io - Client listens to data changes from server automaticallySocket.io - 客户端自动监听来自服务器的数据变化
【发布时间】: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


    【解决方案1】:

    您最好为每个游戏创建房间/频道并将所有玩家连接到该房间(从客户端),而不是发出 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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2018-06-28
    • 2020-09-01
    • 1970-01-01
    • 2018-11-02
    相关资源
    最近更新 更多