简体   繁体   中英

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. 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.

How to listen to this event in React and update the message array? 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. This way, I can easily address message to specific persons in the client. Once sent, the messages are stored in a MongoDB database.

Here is the back-end. The point of interest is 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. Everything works but the "privateMessage" part.

 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.

React must load all events at the beginning.

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.

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);
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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