D
D
Dimash Kenzhegaliev2021-01-05 18:40:24
Node.js
Dimash Kenzhegaliev, 2021-01-05 18:40:24

How to index WebSocket connections of the ws library?

hello, I'm making a simple chat, but with one feature that you can reply to messages to people through the telegram bot, so the problem is that when I write a response from a telegram, the message is sent to all users who are connected, and I have already tried a lot, but here's what I got

bot.start((ctx) => {
      console.log(ctx.update.message.chat)
      ctx.reply('Welcome')
    })
    
    wss.on('error', err => {
      console.log(err)
    })
    wss.on('connection', async ws => {
      const newConnection = {
        uid: uid(16),
        connection: ws
      }
      clients.add(newConnection)

      bot.command('send', (ctx) => {
        const telegramMessage = ctx.message.text.replace('/send', '')
        const queryConnectionUID = telegramMessage.substr(telegramMessage.indexOf('uid: ') + 5, telegramMessage.indexOf(';') - 6)
        ctx.reply(queryConnectionUID)
        clients.forEach(client => {
          if (client.uid === queryConnectionUID) {
            client.connection.send(JSON.stringify({
              action: 'sendMessage',
              agent: 'telegram',
              data: {
                result: true,
                phoneNumber: '+7(777)-777-77-77',
                userName: 'Administrator',
                message: telegramMessage.substr(telegramMessage.indexOf(';') + 2)
              }
            }))
          } else {
            ctx.reply(`uid is wrong; ${client.uid} != ${queryConnectionUID}`)
          }
        })
      })
      bot.launch()

      ws.on('message', async msg => {
        msg = JSON.parse(msg)
        const data = msg.data

        if (msg.action === 'check') {
          bot.telegram.sendMessage('-32432344', 
            `new message sended from\nuid: ${newConnection.uid}\nname: ${data.userName}\nphone: ${data.phoneNumber}\nmessage:\n  ${data.message}`
          )
        }
        else if (msg.action === 'message') {
          const result = await mongoMessages.updateOne({ phoneNumber: data.phoneNumber }, {$push: { messages: data.message }})
          ws.send(JSON.stringify({
            action: 'sendMessage',
            agent: 'server',
            data: {
              result: result,
              phoneNumber: data.phoneNumber,
              userName: data.userName,
              message: data.message
            }
          }))
        }
      })

      ws.on('close', () => {
        clients.delete(ws)
        console.log(`deleted: ${ws}`, clients)
      })
    })
    bot.launch()

this is the main piece of code, I think that I'm too clever and I think that it can be done easier, the main problem is that when creating a connection, I give it a uid, and when disconnecting, I don't know which connection to remove from the array, because as far as I understand disconnect is nothing does not return

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Bazyn, 2021-01-12
@Giranda22-Git

If I understand the problem correctly

wss.on('connection', async ws => {
    const newConnection = {
        uid: uid(16),
        connection: ws
    }
    clients.add(newConnection)

    ws.on('disconnect', () => {
       //clients похоже на Set, тогда так. Или отфильтровать через newConnection.uid если простой массив.
       //newConnection доступна нам тут вследствии замыкание.
        clients.delete(newConnection);       
    });
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question