express node.js

socket.on event gets triggered multiple times

var express = require('express');
var app = express();
var server = app.listen(3000);
var replyFromBot;
var socket = require('');
var io = socket(server);
io.sockets.on('connection' , newConnection);
function newConnection(socket) {
listen = true;
socket.on('Quest' ,reply);
function reply(data) {
replyFromBot = bot.reply("local-user", data);
console.log( " "+replyFromBot);
socket.emit('Ans' , replyFromBot);

i’ve created a server based chat-bot application using node.js and express but the thing is for first time when i call socket.on it gets executed once and for 2nd time it gets executed twice for 3rd thrice and so on i’ve tackled this issue by setting a flag on my client so that it would display only once. i just wants to know is my code logically correct i mean is this a good code? because if the client ask a question for 10th time than listeners array will have 10+9+8….+1 listeners it would go on increasing depending upon number of questions clients asked. which is not good

i tried using removeListener it just removes listener once and it dosent call back for 2nd time. what do you guys recommend? do i go with this or is there any other way to add the listener when socket.on called and remove it when it gets executed and again add listener for the next time it gets called


client code:

function reply() {
socket.emit('Quest' , Quest);
flag = true;;
socket.on('Ans', function(replyFromBot) {
if(flag) {
var para = document.createElement("p2");
x = document.getElementById("MiddleBox");
x.scrollTop = x.scrollHeight;
flag = false;