Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.emit brings multiple values

socket.emit inside socket.on concatenating the same value after every emitting. Here is my code on server-side

io.on('connection', function(socket){
let balance = 6000;


console.log('a user connected');

  socket.on('giveValue',function(data){
        if(data.msg==="New Value"){
          let x = Math.floor(Math.random() * 100 - 50);
          balance += x;
          socket.emit('takeValue',{balance:balance,value:x});
        }
  });

  socket.on('disconnect',function(){
      console.log('User disconnected');
  });
  socket.on('getBalance',(data)=>{
    if(data.msg==='bringBalance'){
      socket.emit('ubalance',{data:balance});
    }
  })

});

And this one is on client side, for client side I'm using Angular 6

constructor() {
    this.socket = io('http://localhost:4000');
  }

  ngOnInit() {
    this.socket.emit('getBalance',{msg:"bringBalance"});
    this.socket.on('ubalance',(data)=>{
      console.log(data);
      this.balance=data.data;
    });
  }

  getSum(event) {
    this.socket.open();
    this.socket.emit('giveValue',{msg:"New Value"});
    this.socket.on('takeValue', (data) => {
       this.balance=data.balance;
       console.log("Value====="+data.value) + "\n";
       console.log("Balance======"+data.balance);

    });
  }

After every click runs getSum() function and its generating random values in back-end add that values to balance.All this doing my back-end side. So the issue is that socket.on("takeValue") after every click brings one more same value.How can I fix this part.Sorry for my language mistakes, I hope you understood me.Thanks for attention and for help.

like image 564
Jor Khachatryan Avatar asked Mar 25 '26 08:03

Jor Khachatryan


1 Answers

Your problem is that you declare .on events inside the functions and each time you run the function, you set new listener to takeValue event. Try below snippet or somthing like this

constructor() {
    this.socket = io('http://localhost:4000');
}

this.socket.on('ubalance',(data)=>{
    console.log(data);
    this.balance=data.data;
    });

this.socket.on('takeValue', (data) => {
    this.balance=data.balance;
    console.log("Value====="+data.value) + "\n";
    console.log("Balance======"+data.balance);

    });

ngOnInit() {
    this.socket.emit('getBalance',{msg:"bringBalance"});

}

getSum(event) {
    this.socket.open();
    this.socket.emit('giveValue',{msg:"New Value"});

}
like image 80
Milad Aghamohammadi Avatar answered Mar 27 '26 21:03

Milad Aghamohammadi