【问题标题】:Issue with socket.io updating component to show new message in chatroomsocket.io 更新组件以在聊天室中显示新消息的问题
【发布时间】:2017-03-05 23:19:26
【问题描述】:

我正在使用 React、Node/Express 和 socket.io 构建一个聊天应用程序。我通过 http.createServer 成功地将我的套接字设置为我的快速服务器。我在客户端和服务器上有一个监听器,用于监听进入聊天室的新消息。理想情况下,我希望在有其他消息时更新聊天的每个实例,就像曾经存在的任何聊天室一样 :)

现在我在客户端和服务器之间成功监听了。我知道是因为 console.log 服务器端。但是,当我从其他实例提交新消息时,我不会重新呈现聊天组件。

所以我在客户端(同样是 React)组件中的代码如下,我在 index.html 中使用带有脚本标签的套接字 CDN(未显示脚本标签):

套接字 CDN 在这里

var socket = io('')

这就是你看到客户端的套接字:

componentDidMount() {
  return axios.get(`api/messages`)
    .then((result) => {
      if (result.data.length) {
        this.setState({ 
          messages: [ ...this.state.messages, ...result.data] 
        } , () => { 
          console.log("The state after messages are mounted : ", this.state) 
        })
      }
    })
    .catch((err) => { throw err})
      socket.on('new message', msg => {
      this.newMessage(msg);
    })
};

newMessage(msg) {
  this.setState({
    messages: [...this.state.messages, msg]
  }, () => {
    this.setState({ message: '' })
    return this.scrollToBottom()
  });
};


onSubmitMessage(event) {
  event.preventDefault();
  const content = this.state.message;

  const msg = {
    content,
    createdAt : new Date(),
    userId : "one",
    chatRoomId : "two"
  }
  axios.post(`api/messages/`, msg)
  .then(() => {
    this.newMessage(msg);
    socket.emit('new message', msg); //HERE'S THE SOCKETS IN ACTION
  })
};

这里是服务端代码Node/Express:

//in server.js
const io = new socketIo(server)
require('./socketEvents')(io);
const connections = [];

然后是我的套接字事件的单独文件 //在socketEvents.js中

module.exports = (io) => {

  io.on('connection', (socket) => {
    console.log("Beautiful sockets are connected")

    socket.once('disconnect', () => {
      console.log("socket is disconnected");
    });

    //DOESN'T DO ANYTHING YET 
    socket.on('join global', (username) => {
      socket.join(username);
      console.log("New user in the global chat : ", username)
    });

    socket.on('new message', (msg) => {
      console.log("The new message from sockets : ", msg);
      socket.emit('new message', msg.content);
    });

  });
}

我的套接字服务器端与客户端链接。我只是没有在不同的情况下看到新消息。是不是因为服务器收到消息后我没有重新渲染?

提前致谢,如果您需要我澄清任何事情,请告诉我。

干杯!

【问题讨论】:

    标签: javascript node.js sockets reactjs socket.io


    【解决方案1】:

    我想通了...我将在这篇文章中留下一个演练,以帮助其他遇到套接字问题的人。我可能会发布一篇关于它的博客。如果我这样做会更新。

    因此,代码在客户端侦听要在我的 onSubmitMessage 函数内部发送的消息。

    onSubmitMessage(event) {
      event.preventDefault(); //prevents HTML <form> from going on its own post
      const content = this.state.message;
    
      //Create message object
      const msg = {
        content,
        createdAt : new Date(),
        userId : "one",
        chatRoomId : "two"
      }
    
      //HERE'S THE IMPORTANT PART!!!
      axios.post(`api/messages/`, msg)
      .then(() => {
    
        // wrapped in a promise, send a handler to server called 
        // ('new message') with the message object
        this.newMessage(msg);
        socket.emit('new message', msg);
      })
      .then(() => {
        //Another promise then waits for the handler to come back from server 
    
        //*****IMPORTANT*************
        //Then invoke newMessage function to get the post on all sockets
        socket.on('message', (msg) => {
          this.newMessage(msg);
        })
      })
    

    };

    现在在服务器端发生了这样的事情:

    // This is where the listener is for the client side handle
    socket.on('new message', (msg) => {
      // broadcast.emit will send the msg object back to client side and
      // post to every instance expcept for the creator of the message
      socket.broadcast.emit('message', msg);
    });
    

    所以数据路径是(C)客户端,(S)服务器:

    从用户那里接收消息对象并-------->

    (C)socket.emit('新消息') -----> (S) socket.on('新消息') -------> (S) socket.broadcast.emit( '消息') --------> (C)socket.on('消息')

    回到客户端,我可以调用我的 newMessage 函数,它会将消息设置为状态,以便我可以显示它。

    我希望有人觉得这很有用!令人惊讶的是,这似乎在 Stack 上相对没有答案。如果有人有任何问题,请随时提出!

    【讨论】:

    猜你喜欢
    • 2013-11-12
    • 2020-01-28
    • 2021-11-14
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    相关资源
    最近更新 更多