dynamic chatting room with io.of()

Asked by At

I'm making chatting server with socket.io.

When the user creates chatting room then

    socket.on('create', data => {
      room.to(mainPage).emit('message', data.roomId)
      require('./channals')(io, data.roomId)
      console.log(JSON.stringify(data) + 'room is created')
    })

It worked find till I tried restart the chatting server.

The namespace of the room saved only in RAM and "create" event only occurs when room is created so when I restart the server and tried join the room then "Invalid namespace" error occurs.

So I tried below code snippet when user join the room.

    socket.on('joinChannal', data => {
      require('./channals')(io, data.roomId)
      console.log(`Joined in ${data.roomId} `)
    })

But, every event that user join the room, socket is created.

What I want to do is checking first visit and if first visit then create new socket if not, do nothing.

example:

const rooms = new Set()
// ...
    socket.on('joinChannal', data => {
      if (rooms.has(data.roomId)) { // do nothing. }
      else { rooms.add(data.roomId); require('./channals')(io, data.roomId) }
    })
// ...

Am I doing right approach?

Here is my code.

module.exports = (io, roomId) => {
  const room = io.of(`/${roomId}`)
  const pageName = roomId

  room.on('connection', socket => {
    room.clients((err, clients) => {
      if (err) throw err
      console.log(clients)
    })

    socket.on('join', data => {
      socket.join(pageName)
    })

    // @params: data: {roomId: string, msg: string}
    socket.on('create', data => {
      room.to(pageName).emit('message', data)
    })

    socket.on('leave', () => {
      socket.leave(pageName)
    })

    socket.on('disconnect', () => {
      socket.disconnect(true)
    })

    socket.on('error', err => {
      console.log(err)
      socket.disconnect(true)
    })

    // @params: data: {roomId: string, userId: number}
    socket.on('joinToWrite', data => {
      room.to(pageName).emit('message', data)
    })
  })
}
module.exports = io => {
  const room = io.of('/mainpage')
  const mainPage = 'mainpage'
  let sockets = []

  room.on('connection', socket => {
    sockets.push(socket)

    socket.on('join', () => {
      socket.join(mainPage)
    })

    socket.on('create', data => {
      room.to(mainPage).emit('message', data.roomId)
      require('./channals')(io, data.roomId)
    })

    socket.on('joinChannal', data => {
      require('./channals')(io, data.roomId)
    })

    socket.on('leave', () => {
      sockets.splice(sockets.indexOf(socket), 1)
      socket.leave(mainPage)
    })

    socket.on('disconnect', () => {
      sockets.splice(sockets.indexOf(socket), 1)
      socket.leave(mainPage)
    })

    socket.on('error', err => {
      console.log(err)
    })
  })
}

Please let me know if you need more info.

Thanks.

0 Answers