lado do server

mail@pastecode.io avatar
unknown
javascript
2 years ago
1.8 kB
1
Indexable
Never
let chatMessages = []
let allUsers = []
let queue = []


var test = async (socket) => {

    if (queue.length > 0) {

        let peer0 = queue[queue.length - 1]

        queue.pop()

        console.log(`${peer0.id} saiu do queue.`)
        console.log(queue)

        var room = `${socket.id}#${peer0.id}`

        peer0.join(room)
        socket.join(room)

        console.log(`${socket.id} e ${peer0.id} entraram na sala: ${room}`)

        peer0.emit('chat start', { 'name': socket.id, 'sala': room });
        socket.emit('chat start', { 'name': peer0.id, 'sala': room });
    } else {
        queue.push(socket)
        console.log(`${socket.id} entrou no queue`)
    }

}



router.get('/chat', (req, res) => {


    console.log('io')

    io.once('connection', async (socket) => {

        let user = {
            nome: req.user.usuario,
            socket: socket.id
        }

        allUsers.push(user)

       test(socket)

        

        socket.on('user', (user) => {
            socket.on('room', room => {
                socket.to(room).emit('userArrive', user)
            })
            
        })

        console.log(`Conectado: ${socket.id}`)




        socket.on('sendMessage', data => {
            chatMessages.push(data)
            socket.on('room', room => {

                socket.to(room).emit('receivedMessage', data)

            })
            
        })

        socket.on('disconnect', () => {
            console.log(`Desconectado: ${socket.id}`)
            console.log(`O usuario: ${user.nome} saiu do chat.`)
            allUsers.split(allUsers.indexOf(user), 1)


        })



    })

    res.render('chat/chat', { messages: chatMessages })


})