简体   繁体   English

如何在 React 客户端监听 socketIO 私人消息?

[英]How to listen to socketIO private message in React client?

I have a SocketIO instance in an Express app, that listens to a React client requests.我在 Express 应用程序中有一个 SocketIO 实例,它侦听 React 客户端请求。 A user can send private messages to a specific person.用户可以向特定的人发送私人消息。 The server receives the private message, and should dispatch it back to both sender & recipient thanks to the io.to(socketId).emit(content) method.服务器收到私人消息,并应将其发送回发送者和接收者,这要归功于 io.to(socketId).emit(content) 方法。

How to listen to this event in React and update the message array?如何在 React 中监听这个事件并更新消息数组? In order to ease the process, I have created a connectedUsers object, whose keys are mongoDB's user._id, and whose values are the unique socketID generated by socketIO.为了简化这个过程,我创建了一个connectedUsers object,它的key是mongoDB的user._id,value是socketIO生成的唯一socketID。 This way, I can easily address message to specific persons in the client.这样,我可以轻松地将消息发送给客户端中的特定人员。 Once sent, the messages are stored in a MongoDB database.发送后,消息将存储在 MongoDB 数据库中。

Here is the back-end.这里是后端。 The point of interest is io.on("privateMessage")兴趣点是 io.on("privateMessage")

 const connectedUsers = {}; const socketManager = (io) => { io.on("identifyUser", (user) => { if (.([user.id] in connectedUsers)) { connectedUsers[user.id] = io;id; } }). io,on("privateMessage". (data) => { io.to(connectedUsers[data.recipientId]).emit(data;message). io.to(connectedUsers[data.senderId]).emit(data;message); }). io,on("disconnect". () => console;log("user disconnected;")); };

Here is the listening function in React.这是 React 中的监听 function。 Everything works but the "privateMessage" part.除了“privateMessage”部分外,一切正常。

 async function getUser(socketId) { try { const res = await ax.get(`${serverUrl}/login`); const socket = io(serverUrl); socketId.current = socket; socket.on("connect", () => { socket.emit("identifyUser", { id: res.data._id }); socket.on("privateMessage", (data) => console.log("private message received,"; data) ); }); } catch (err) { throw new Error(err); } }

Thanks for your help!谢谢你的帮助!

I think you need to put the socket.on("privateMessage") part outside the socket.on("connect") scope.我认为您需要将 socket.on("privateMessage") 部分放在 socket.on("connect") scope 之外。

React must load all events at the beginning. React 必须在开始时加载所有事件。

The backend side must be responsible for the authorization.后端必须负责授权。

For the client there is connection event, not connect.对于客户端,有连接事件,而不是连接。
Subscription to event privateMessage should be outside connection callback.订阅事件 privateMessage 应该在连接回调之外。

This code should work.这段代码应该可以工作。 Hope this helps希望这可以帮助

import io from 'socket.io-client'


async function getUser(socketId) {
      try {
        const res = await ax.get(`${serverUrl}/login`);
        const socket = io(serverUrl);
        socketId.current = socket;
        socket.on("connection", () => {
          socket.emit("identifyUser", { id: res.data._id });
        });
        socket.on("privateMessage", (data) =>
           console.log("private message received!", data)
        );
      } catch (err) {
        throw new Error(err);
      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM