套接字.IO判断用户是在线还是离线



我们可以通过以下代码跟踪连接是建立还是断开

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

嗯,很好。但是我们如何确定是哪个用户连接了还是离线了呢?我的客户端是用PHP/HTML编写的,所以他们有一个用户ID。

如果您的客户端有特定的用户id,他们需要将它们发送到套接字。io服务器。例如,在客户端,您可以执行

// Browser (front-end)
<script>
 const socket = io();
 socket.emit('login',{userId:'YourUserID'});
</script>

在服务器端你可以输入

// server (back-end)
const users = {};
io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('login', function(data){
    console.log('a user ' + data.userId + ' connected');
    // saving userId to object with socket ID
    users[socket.id] = data.userId;
  });
  socket.on('disconnect', function(){
    console.log('user ' + users[socket.id] + ' disconnected');
    // remove saved socket from users object
    delete users[socket.id];
  });
});

现在您可以将套接字ID与您的用户ID配对并使用它。

除了@galethil的回答,如果用户打开多个选项卡(套接字连接),每个选项卡(套接字连接)对于单个用户有唯一的套接字id,所以我们需要为特定用户管理套接字id数组,

客户端连接:支持Socket IO Client v3.x,

<!-- SOCKET LIBRARY IN HTML -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.5/socket.io.js"></script>
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
    upgrade: false,
    query: queryParams,
    reconnection: false,
    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
    });
});

服务器端连接:支持Socket IO Server v3.x,

  • 依赖性:
const _ = require("lodash");
const express = require('express');
const app = express();
const port = 3000; // define your port
const server = app.listen(port, () => {
  console.log(`We are Listening on port ${port}...`);
});
  • 连接:
const io = require('socket.io')(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
  });
});

GitHub演示

我们可以识别服务器上的套接字id,哪些是连接的,哪些是断开的。你可以这样做。如果在客户端

中有标识符,则可以使用此设置。

socket.emit('login', userId);
服务器端

const users = {};
io.on("connection", (socket) => {
   socket.on("login", (data) => {
      users[socket.id] = data;
    });
  socket.on("disconnecting", (reason) => {
    
    delete users[socket.id]; // remove the user. -- maybe not the exact code
  });
});

希望你明白。

相关内容

  • 没有找到相关文章

最新更新