Answer the question
In order to leave comments, you need to log in
In which Vue 3 life cycle to close the websocket connection after the client closes the site?
I'm trying to send a message to the server with the token.id of the client when he leaves the site, in order to remove it from the array that counts the online site and eventually close the socket connection, but nothing happens, how can I do it right or in what life cycle is it is being done?
//client side
beforeUnmount(){ //или unmounted()
this.$socket.emit('exit', this.token_id);
}
//server side
var users = []; //tokenы всех пользователей
socket.on('exit', data => {
console.log(data) //ничего не приходит дабы сделать filter по массиву users
users = users.filter(u => u !== data);
})
Answer the question
In order to leave comments, you need to log in
You need to understand what you mean by the phrase "when the client leaves the site", and what specific web sockets you use - standard, or either Socket.io working on Websocket transport.
// https://socket.io/docs/v4/server-initialization/
import * as Server from 'socket.io'
const io = Server()
io.listen(3000)
// коллекция сокет-подключений
const connections = new Set()
// когда Socket.io сервер словил новое подключение
io.on('connection', (s) => {
// добавляем это подключение в коллекцию
connections.add(s)
// слушаем событие отключения сокета и реагируем на него
s.once('disconnect', () => {
// удаляем данное сокет-подключение из коллекции
connections.delete(s)
})
})
// connections.size - покажет размер коллекции, то есть количество подключенных клиентов к серверу Socket.io (онлайн на сайте в вашем случае)
// https://socket.io/docs/v4/server-instance/#Server-engine
io.engine.clientsCount
// или:
// https://socket.io/docs/v4/server-api/#namespace-allSockets
await io.allSockets()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question