socket.io正在连续调用中调用多个实例

我正在尝试在我的MEAN-stack项目中创建一个好友请求功能,该功能使用socket.io是实时的

这是我的代码:

客户端组件

import { Component,OnInit } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { AppService } from '../../services/app.service';
import { FriendListsocketService } from './../../services/friend-list-socket.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-user-friends',templateUrl: './user-friends.component.html',styleUrls: ['./user-friends.component.css'],// providers: [FriendListsocketService]
})
export class UserFriendsComponent implements OnInit {


  public userList:any=[];
  public userId:String=''; //userId of the logged in user.

  constructor(
    public appService:AppService,public friendSocketService:FriendListsocketService,public cookies:CookieService,public router:Router) { }

  ngOnInit() {
    this.userId=this.cookies.get('userId');
    this.getOtherUsers(this.userId); //loading the other users in the add friends page.
    this.listLoader(this.userId); //informs the view if any request comes from friend.
  }

  public getOtherUsers:any=(userId)=>{
    this.appService.userList(userId).subscribe((apiResponse)=>{
      console.log(apiResponse);
      this.userList=[];
      if(apiResponse.status===200){
        this.userList=apiResponse.data;
      }else {
        this.toastr.warning(apiResponse.message);
      }
    })
  } //this func is to get the users who are not friends from the backend. call this whenever the list is needed.

  public addFriend(friendId){

    this.appService.addFriend(this.userId,friendId).subscribe((apiResponse)=>{
      console.log(apiResponse);
      if(apiResponse.status===200){
        this.getOtherUsers(this.userId);
        let data={
          action:'add',message:'Add Request sent',sender:this.userId,receipient:friendId
        }
        this.friendSocketService.notifyFriend(data);
      }else {
        this.toastr.warning(apiResponse.message);
      }
    });

  }

  public listLoader:any=(userId)=>{
    this.friendSocketService.listReload(userId).subscribe((apiResponse)=>{
      if(apiResponse.action==='add'){
        console.log("list Loader called.");
        this.getOtherUsers(userId);
      }else if(apiResponse.action==='delete'){
        console.log("Request Deleted");
        this.getOtherUsers(userId);
      }

    })
  }
}

客户端服务

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs';
import { HttpClient,HttpErrorResponse } from '@angular/common/http';
import { CookieService } from 'ngx-cookie-service';

// @Injectable()

@Injectable({
  providedIn: 'root'
})
export class FriendListsocketService {

  private url = "http://localhost:3000/";
  private socket;

  constructor(public http:HttpClient,public cookie:CookieService) { 
    this.socket=io(this.url); // connection is being created. i.e the handshake is happening here.
    console.log("socket connected",data);
  }

  public listReload=(userId)=>{
    return Observable.create((observer)=>{
      this.socket.on(userId,(data)=>{
        observer.next(data);
      })
    })
  }//this shall listen to calls from backend on userId if any friend statuses change,then it shall inform the component.

  public notifyFriend=(data)=>{
    this.socket.emit('notifyFriend',data);
  }
}

服务器端

let setServer = (server) => {

    let io = socketio.listen(server);

    let myIo = io.of('/');

    myIo.on('connection',(socket) => {

        console.log("on connection--functions are ready");

        socket.on('notifyFriend',(data) => {      //here the friendId is received to whom the message has to be sent.

            if (data.action === 'add') {
                let response = {
                    message: 'Friend Request Received',action: 'add'
                }
                myIo.emit(data.receipient,response);
            } else if (data.action === 'delete') {
                let response = {
                    message: 'Friend Request Received',action: 'delete'
                }
                myIo.emit(data.receipient,response);
            } else if (data.action === 'accept') {
                let response = {
                    message: 'Friend Request Received',action: 'accept'
                }

                myIo.emit(data.receipient,response);
            }

        })
    })
}

问题在于,每当我尝试进行套接字间通信时,消息就会越来越多。例如:当我尝试接受/删除请求时,我在接收方收到多条消息。请帮忙解决这个问题,因为我无法理解如何设置多个请求,而我只拨打一次服务。

注意:我以前也曾尝试在组件中提供服务,但是我也收到了相同的多个呼叫。

socket.io正在连续调用中调用多个实例

在这里 user-home.component.ts user-friends.component.ts 被调用,因为user-home中也有一个侦听器,并且该服务在根本身启动。

a65758872 回答:socket.io正在连续调用中调用多个实例

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3164545.html

大家都在问