그저 내가 되었고

🌟socket.io:: 프로젝트 내에서 router로 분리하기(작성중) 본문

개발/socket.io

🌟socket.io:: 프로젝트 내에서 router로 분리하기(작성중)

hyuunii 2022. 12. 10. 23:37

 

라우터 파일에서는

function app2(io){

router.get('/sports', function(요청, 응답){
  io.어쩌구()
});

return router
}

module.exports = app2;

 

+ 라우터파일을 require할 때는 require(라우터파일경로)(io) 이렇게 쓰기

 

+ server.js에서는 app.set('io', io)하고 app.get() 여기 넣지 말고 그냥 밖에다가 io. 이렇게 쓰기

 

const SocketIO = require("socket.io");

module.exports = (server, app) => {
  const io = SocketIO(server, { path: "/socket.io" });
  
  // express에서 변수를 저장하는 방법
  // req.app.get("io")로 사용 가능합니다. 
  app.set("io", io)

  
  ... 이하 중략
req.app.get("io").of("/room").emit(key, value)

 

실제 사용한 예시

router.post("/room", async (req, res, next) => {
  try {
  
    // mongoose를 이용해 데이터를 생성 후 저장  
    const room = new Room({
      title: req.body.title,
      max: req.body.max,
      owner: req.session.color,
      password: req.body.password,
    });
    const newRoom = await room.save();

    // io 객체를 가져와서 room 네임스페이스에 newRoom 키를 가진 메세지를 emit합니다.
    const io = req.app.get("io");
    io.of("/room").emit("newRoom", newRoom);
    
    // 소켓 통신을 처리했으니 리다이렉트처리합니다.
    res.redirect(`/room/${newRoom._id}?password=${req.body.password}`);
  } catch (error) {
    console.error(error);
    next(error);
  }
});