node.js - Socket.io 事件多次发出

标签 node.js reactjs socket.io

我正在创建一个带有实时通知的聊天应用程序,通知会被发送,但它们会被发送随机次数,而它们应该只发送一次。我在前端使用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})(通知);

最佳答案

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

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

关于node.js - Socket.io 事件多次发出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56624768/

相关文章:

python - 格式化消息以从 python 客户端发送到 socket.io node.js 服务器

node.js - NodeJS + Socket.io 连接断开/重新连接?

node.js - Express/node 服务器随机崩溃,events.js ECONNRESET

reactjs - 如何在React中处理多个路由器

node.js - 使用 webrtc + node.js 进行视频 session

javascript - 与 Redux react : Module build failed: SyntaxError: Unexpected token <

javascript - 将鼠标悬停在 Chrome 上的 React 中数字输入的递增/递减值按钮上会导致持续增加

node.js - 在Socket.IO中, 'heartbeat'是可以用来触发其他 Action 的事件吗?

node.js - sequelize中如何设置复杂的join条件?

node.js - 处理 JWT 验证失败