【问题标题】:React/Socket.io - Client emits to all other clients only once and then only emits to itself after thatReact/Socket.io - 客户端只向所有其他客户端发出一次,然后只向自己发出
【发布时间】:2020-08-19 07:26:00
【问题描述】:

遇到 React/Socket.io 问题。我有两个不同的套接字发射器/侦听器:一个用于聊天,一个用于跟踪应用程序的实时更改。我有两个运行 localhost 的单独窗口。问题是当我在一个窗口上发出更改时,另一个窗口可以第一次收到该更改,但再也不会收到该更改(即获得第一条聊天消息但没有后续消息)。在第一次发射/接收之后,发送客户端开始接收自己的发射器。

前端代码: `

socket = io("localhost:3002");
componentDidMount() {
    //get id from url
    const { id } = this.props.match.params;

    //join specific room for project
    this.socket.on("connect", () => {
      this.socket.emit("room", this.projectId);
    });

    //listener for incoming messages
    this.socket.on("RECEIVE_MESSAGE", (data) => {
      this.props.addChat(this.projectId, data);
    });

    this.socket.on("UPDATE_PROJECT", () => {
      console.log("update");
      this.props.fetchProject(id);
    });
  }
emitTaskChange = () => {
    this.socket.emit("TASK_CHANGE", { data: null });
  };
onChatSubmit = (e) => {
    e.preventDefault();

    //create object with current user as author, message, and a timestamp
    const chat = {
      author: this.props.currentUser.name,
      message: this.state.newChat,
      createdAt: new Date().toLocaleString(),
    };

    //send message through socket
    this.socket.emit("SEND_MESSAGE", chat);

    //call action creator to add new chat
    this.props.addChat(this.projectId, chat);

    this.setState({ currentMessage: "" });
  };

handleTaskEdit = (taskId, currentStatus) => {
    const newStatus = currentStatus === "todo" ? "inprogress" : "completed";
    this.props.editTask(this.projectId, taskId, newStatus);
    this.emitTaskChange();
  };

`

后端代码: `

const io = socket(server);

//create separate chat rooms using project id
io.on("connection", (socket) => {
  socket.on("room", (room) => {
    socket.join(room);
    socket.in(room).on("SEND_MESSAGE", (message) => {
      socket.emit("RECEIVE_MESSAGE", message);
    });
    socket.in(room).on("TASK_CHANGE", (data) => {
      socket.emit("UPDATE_PROJECT", data);
    });
  });

`

【问题讨论】:

    标签: reactjs socket.io


    【解决方案1】:

    发现错误: 不得不从 socket.on 更改服务器端代码,而是使用已初始化的 io 对象,例如 io.sockets.on

    【讨论】:

      猜你喜欢
      • 2017-08-07
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多