首页 > 解决方案 > Socket IO 监听所有 Sessions id

问题描述

我有一个带有 Redux 和持久化器的 Socket IO 和 Session 的应用程序。问题是每个会话的套接字当时正在侦听我的应用程序中打开的所有会话。

示例:我在 client1 上并登录以进入应用程序。我每分钟收到 100 个请求(根据我的 Socket 设置)。如果客户端 2 也进入应用程序,我(客户端 1)和他(客户端 2)将开始每分钟接收 200 个请求。如果client3进入,我们三个人每分钟会收到300个请求,以此类推。

也就是说,client1 会话套接字正在侦听应用程序中所有打开的会话,并且应该只侦听来自记录在其特定会话中的 client1 的请求。

服务器:

const ioServer = require('http').createServer(server)

class IoConta {
  constructor () {
    let getNotifications

    io.on('connection', socket => {

      if (getNotifications) clearInterval(getNotifications)

    socket.on('getNotifications', async data => {
          getNotifications = setInterval(
          () => this.getNotifications(data.id),
          2000
        )
      })

    io.on('disconnect', () => {
      clearInterval(getNotifications)
    })

    ioServer.listen(3901)
 }

async getNotifications (id) {
    const novas = await Notificacoes.find({
      conta: id,
      read: false
    })

    io.emit('notifications', { notifications: novas, conta: id })
  }

正面:


const urlIO = 'http://localhost:3901'

const signOut = () => {
    useEffect(() => {
        const socket = io(urlIO)
        socket.emit('getNotifications', { id: profile.id })
        socket.on('notifications', data => {
            if (profile.id === data.conta) { 
            dispatch(someDispatch(data)) }
            })
}, [])

我需要 Socket 只监听来自登录到特定会话的客户端的请求,也就是说,每个客户端都有自己的与链接到其 id 的套接字的连接。我做错了什么,例如,通过.on在套接字的“连接”内部调用,还是什么?我很感激帮助

标签: javascriptnode.jsreactjssocket.io

解决方案


推荐阅读