Socket.io 事件多次发出

Posted

技术标签:

【中文标题】Socket.io 事件多次发出【英文标题】:Socket.io event emitting multiple times 【发布时间】:2019-10-30 15:52:05 【问题描述】:

我正在创建一个带有实时通知的聊天应用程序,通知会被发送,但它们会随机发送多次,而应该只发送一次。我在前端使用 react,在后端使用 node.js。

这是我的套接字事件:

socket.on('sendNotification', function(recipientId, notification) 
        console.log('send notification is firing');
      //find the room where the title is the recipient
      Room.findOne('title':  recipientId, function(err, room)
        if(err) throw err;
        console.log('this is the notification room found', room.id);
        socket.broadcast.to(room.id).emit('addNotification', notification);
      );
       socket.join(theRoom.id);
    );

// // //这应该在客户端上

   socket.on('joinYourNotificationRoom', function(userId)
    Room.findOne('title' :userId, function(err, room)
        if(err) throw 'thisd is the error to join your notifiaction room' + err;
        if(room)
          console.log('about to join a your notification room ');
        socket.join(room.id);
      else
        Room.create(
          title: userId
        , function(err, newRoom, socket)
         socket.join(newRoom.id);
         console.log('new notifaction room created');
       );
     ;
   );
);

这是我在前端发送消息后发送通知的地方:

console.log('these are the users in the application', this.state.users);
let theUsers = [].concat.apply([], this.state.users);
console.log('theUsers', theUsers);

for(let user of theUsers)
  console.log('this is one of the users', user);
  if(user._id !== this.props.auth.user.id)
    let notification = ;
    let notificationText = user.name + " sent a message in room " + this.props.currentRoom.title;
    notification.recipient = user._id;
    notification.text = notificationText;
    console.log('join notification about to be submitted', user._id);
    this.state.socket.emit('sendNotification', user._id, notification);
  

这是我在前端的通知室:

import React,  Component  from 'react';
import  connect  from 'react-redux';
import io from 'socket.io-client';
import notificationToServer, getNotifications from 
 '../../actions';
import NotificationContainer from './NotificationContainer';
import axios from 'axios';

const socketURL="http://localhost:3000";
class Notifications extends Component 
  constructor(props)
    super(props);
    this.state = 
      notifications:[],
      socket:null
    
    this.initSocket();
  

  initSocket = () =>
    const  user  = this.props.auth;
    const socket = io('http://127.0.0.1:5002', 
    transports: ['websocket'], jsonp: false );
    socket.connect();
    socket.on('connect', ()=>
      this.setState(socket: socket);
      this.state.socket.emit('joinYourNotificationRoom', user.id);
      this.state.socket.on('addNotification', (notification)=>
        this.props.notificationToServer(notification, ()=> 
          console.log('callback fired');
          //clear notifications
          this.props.getNotifications(user.id);
        );
      );
    )
  

  componentWillMount()
    const  user  = this.props.auth;
    this.props.getNotifications(user.id);
  


  render() 
    console.log('these are the notifications', this.props.notification);
    let notifications = this.props.notifications.map((notification)=>
      <NotificationContainer notification=notification />

    );
    return (
      <div className="App">
        <h6>Notifications</h6>
        notifications
      </div>
    );
  


const mapStateToProps = state => 
  return
    auth:state.auth,
    notifications: state.notifications.notifications
  ;
;


export default connect(mapStateToProps,

getNotifications, notificationToServer)(通知);

【问题讨论】:

【参考方案1】:

这应该是由于与服务器创建了多个连接并多次订阅相同的事件。在您的情况下,可以多次调用 initSocket 方法。在initSocket 方法中尝试console.log,并确保它只被调用一次,因为可以创建多个Notification 组件。

如果是这样,请将您的套接字连接逻辑移至单独的文件(ES6 模块)并通过该文件进行通信。

【讨论】:

我 console.logged initSocket 只打印了一次 您好,请您看一下这个问题,非常感谢您的帮助。***.com/questions/65682609/…

以上是关于Socket.io 事件多次发出的主要内容,如果未能解决你的问题,请参考以下文章

Socket.IO 在一个房间内多次发射(与 React.js 一起使用)

socket.io 发出多次

Socket.io 消息事件多次触发

在 socket.io 上从客户端捕获所有事件“发出”

刷新后socket.io客户端多次监听同一事件

socket.io 在 x 秒/第一次尝试获取响应失败后停止重新发出事件