socket.io determine if a user is online or offline

后端 未结 2 942
死守一世寂寞
死守一世寂寞 2020-12-23 15:12

We can trace if a connection is established or disconnected by this code

console.log(\'a user connected\');
    socket.on(\'disconnect\', function () {
              


        
2条回答
  •  时光说笑
    2020-12-23 15:43

    In addition of @galethil's answer, What if user opens more than one tab, each tab has unique socket id for single user, so we need to manage array of socket ids for particular user,

    Client Side Connection:

    
    
    
    const host = "http://yourdomain.com";
    // PASS your query parameters
    const queryParams = { userId: 123 };
    const socket = io(host, {
        path: "/pathToConnection",
        transports: ['websocket'],  // https://stackoverflow.com/a/52180905/8987128
        allowUpgrades: false,
        query: queryParams,
        reconnect: false,
        secure: true,
        rejectUnauthorized: false
    });
    
    socket.once("connect", () => {
        
        // USER IS ONLINE
        socket.on("online", (userId) => {
            console.log(userId, "Is Online!"); // update online status
        });
    
        // USER IS OFFLINE
        socket.on("offline", (userId) => {
            console.log(userId, "Is Offline!"); // update offline status
        });
    
    });
    

    Server Side Connection:

    • Dependencies:
    const _ = require("lodash");
    const express = require('express');
    const app = express();
    const port = 3000; // define your port
    const server = await app.listen(port, () => {
      console.log(`We are Listening on port ${port}...`);
    });
    
    • Connection:
    const io = require('socket.io').listen(server, {
        path: "/pathToConnection"
    });
    let users = {};
    io.on('connection', (socket) => {
    
      let userId = socket.handshake.query.userId; // GET USER ID
      
      // CHECK IS USER EXHIST 
      if (!users[userId]) users[userId] = [];
      
      // PUSH SOCKET ID FOR PARTICULAR USER ID
      users[userId].push(socket.id);
       
      // USER IS ONLINE BROAD CAST TO ALL CONNECTED USERS
      io.sockets.emit("online", userId);
    
      // DISCONNECT EVENT
      socket.on('disconnect', (reason) => {
    
        // REMOVE FROM SOCKET USERS
        _.remove(users[userId], (u) => u === socket.id);
        if (users[userId].length === 0) {
          // ISER IS OFFLINE BROAD CAST TO ALL CONNECTED USERS
          io.sockets.emit("offline", userId);
          // REMOVE OBJECT
          delete users[userId];
        }
       
        socket.disconnect(); // DISCONNECT SOCKET
    
      });
    
    });
    

提交回复
热议问题