简体   繁体   中英

Not able to connect to rooms with socket.io

I'm using socket io in two places in the app:

  1. emiting offers on the main page that everyone can see
  2. emiting chat messages only between two users based on order_id

I was able to set up first use case but not the second. When creating a new message, response status is 500 after hitting the socket part in the controller.

index.js

  const serverIO = server.listen(
    port,
    console.log(`Listening on Port ${port}`)
  );
  const io = require("./socket").init(serverIO);
  io.on("connection", (socket) => {
    socket.join("some room");
    console.log("cient connected");
  });

socket.js

let io;

module.exports = {
  init: (httpServer) => {
    io = require("socket.io")(httpServer);
    return io;
  },
  getIO: (socket) => {
    if (!io) {
      throw new Error("Socket.io not initialized!");
    }
    console.log("socket", socket());
    return io;
  },
};

chatController.js

const io = require("../socket");
const chatModel = require("./chatModel.js");

exports.createChat = async (req, res) => {
  try {
    const savedMessage = await chatModel.saveMessage(req.body);
    if (!savedMessage) {
      return res.status(400).json({
        errorMessage: "Something went wrong with your chat request",
      });
    }
    io.getIO().socket.to(req.body.order_id).emit("newMessage", { action: "create", message: savedMessage });
    return res.status(200).json(savedMessage);
  } catch (error) {
    return res.status(500).json({
      errorMessage: error,
    });
  }
};

on the client, I'm listening like this:

Chat.js

useEffect(() => {
    const socket = openSocket(baseURL);
    socket.on("newMessage", ({ room, data }) => {
      console.log("room", room); //not being reached
      if (data.action === "create") {
        dispatch(addMessage(...data.message));
      }
    });
  }, []);

I tried adding the boilerplate code from documentation but that didn't seem to work.

io.on('connection', socket => {
  socket.join('some room');
});

How can I join rooms based on orderId and listen to said room on the client?

Was able to reach a working solution (chat messages are being broadcast only to the intended recipients)but don't know if it's optimal or efficient.

added socket.join in my index.js file

io.on("connection", (socket) => {
   socket.on("joinRoom", (room) => {
      console.log("joined room");
      socket.join(room);
    });

    console.log("cient connected");
  });

modified my controller

io.getIO().to(req.body.order_id).emit("newMessage", {
      action: "create",
      message: savedMessage,
    });

And on the front end, on mount, I'm joining a room and listening for newMessage from server.

  useEffect(() => {
    const socket = openSocket(baseURL);
    socket.emit("joinRoom", orderId);
    socket.on("newMessage", (data) => {
      console.log("data", data);
      if (data.action === "create") {
        dispatch(addMessage(...data.message));
      }
    });
  }, []);

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