2021-12-02

Redis NOdeJs server error,client is closed

I am developing an application where chats has to cached and monitored, currently it is an local application where i have installed redis and redis-cli. The problem i'm facing is (node:5368) UnhandledPromiseRejectionWarning: Error: The client is closed Attaching code snippet below

//redis setup
const redis = require('redis');
const client = redis.createClient()//kept blank so that default options are available
  

//runs when client connects
io.on("connect", function (socket) {

  //this is client side socket
  //console.log("a new user connected...");

  socket.on("join", function ({ name, room }, callback) {
    //console.log(name, room);
    const { msg, user } = addUser({ id: socket.id, name, room });
   // console.log(user);
    if (msg) return callback(msg); //accessible in frontend

    //emit to all users
    socket.emit("message", {
      user: "Admin",
      text: `Welcome to the room ${user.name}`,
    });
    //emit to all users except current one
  
    socket.broadcast
      .to(user.room)
      .emit("message", { user: "Admin", text: `${user.name} has joined` });

    socket.join(user.room); //pass the room that user wants to join

    //get all users in the room
    io.to(user.room).emit("roomData", {
      room: user.room,
      users: getUsersInRoom(user.room),
    });

    callback();
  }); //end of join

  //user generated messages
  socket.on("sendMessage",  async(message, callback)=>{
    const user = getUser(socket.id);

    //this is where we can store the messages in redis
    await client.set("messages",message);

    io.to(user.room).emit("message", { user: user.name, text: message });
    console.log(client.get('messages'));
    callback();
  }); //end of sendMessage

  //when user disconnects
  socket.on("disconnect", function () {
    const user = removeUser(socket.id);
    if (user) {
     
      console.log(client)

      io.to(user.room).emit("message", {
        user: "Admin",
        text: `${user.name} has left `,
      });
    }
  }); //end of disconnect

I am getting above error when user sends a message to the room or when socket.on("sendMessage") is called.

Where am I going wrong?

Thank you in advance.



from Recent Questions - Stack Overflow https://ift.tt/3plPPYc
https://ift.tt/eA8V8J

No comments:

Post a Comment