R
R
rockwell3232021-05-04 04:21:55
Socket.io
rockwell323, 2021-05-04 04:21:55

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

1 answer(s)
T
Tema Smirnov, 2021-05-04
@rockwell323

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.

  • If you mean closing the browser tab by the client (as an example), then at that moment the browser will break the connection with the socket.io server, and the `disconnect` event will occur on the server for the specific socket that was bound to this connection.
    Moreover - when closing a tab with a site, Vue does not call `beforeUnmount` or `unmounted`, so your code will not work - the client (browser) will not send anything, the server will not receive anything.
    *But this can be implemented by yourself through the `beforeunload` event listener of `window` (although the event will not work if the browser or the OS itself crashes), more details here:
    https://forum.vuejs.org/t/detect-browser- close/5001/2
    https://developer.mozilla.org/en-US/docs/Web/API/B...
    https://developers.google.com/web/updates/2018/07/...
    https://developer.mozilla.org/en-US/docs/Web/API/W...
  • If you mean logging out of the client account on the site, then your code will work

An example of handling the first case (when the client exits the site by closing the tab) on the server side if you use Socket.io (by analogy, you can do it with regular web sockets, but there you will have to detect a connection break based on the absence of a response to ping-pong from the browser):
// 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 (онлайн на сайте в вашем случае)

However, this code can not be used in this form, since Socket.io already has ready-made functions and collections under the hood for working with connected sockets, so there is no need to create and store your own socket connection lists in memory.
For example, in v4, the number/list of connected clients can be obtained in this way:
// 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 question

Ask a Question

731 491 924 answers to any question