socket.on事件被多次触发 [英] socket.on event gets triggered multiple times

查看:705
本文介绍了socket.on事件被多次触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var express = require('express');
var app = express();
var server = app.listen(3000);
var replyFromBot;
app.use(express.static('public'));
var socket = require('socket.io');
var io = socket(server);
io.sockets.on('connection' , newConnection);

function newConnection(socket) {
   console.log(socket.id);
   listen = true;
   socket.on('Quest' ,reply);
   function reply(data) {
     replyFromBot = bot.reply("local-user", data);
     console.log(socket.id+ " "+replyFromBot);
     socket.emit('Ans' , replyFromBot);
  }
}

我已经使用node.js socket.io创建了一个基于服务器的聊天机器人应用程序,并进行了表达,但是事情是我第一次调用socket时第一次执行,第二次执行了两次,第三次执行了两次三次,等等,我已经通过在客户端上设置标志以使其仅显示一次来解决此问题.我只是想知道我的代码在逻辑上是正确的,我的意思是这是一个好的代码吗?因为如果客户第10次提出问题,那么侦听器数组将有10 + 9 + 8 .... + 1个侦听器,它会根据客户提出的问题数量而继续增加.不好

i've created a server based chat-bot application using node.js socket.io 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

我尝试使用removeListener,它只删除一次监听器,并且第二次回调.你们推荐什么?我要这样做吗?还是有其他方法可以在调用socket.on时添加侦听器,并在执行时将其删除,并在下次调用时再次添加侦听器

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

谢谢.

客户代码:

function reply() {
  socket.emit('Quest' , Quest);
  flag = true;
  audio.play();
  socket.on('Ans', function(replyFromBot) {
  if(flag) {
    console.log("hi");
    var para = document.createElement("p2");
    x = document.getElementById("MiddleBox");
    para.appendChild(document.createTextNode(replyFromBot));
    x.appendChild(para);
    x.scrollTop = x.scrollHeight;
    flag = false;
  }
 });
}

推荐答案

问题是由您的客户端代码引起的.每次在客户端中调用reply()函数时,都会设置一个附加的socket.on('Ans', ...)事件处理程序,这意味着它们会累积.您可以将其更改为socket.once(),并在每次收到Ans消息后将其自身删除.然后,您也可以删除flag变量.

The problem is caused by your client code. Each time you call the reply() function in the client you set up an additional socket.on('Ans', ...) event handler which means they accumulate. You can change that to socket.once() and it will remove itself each time after it get the Ans message. You can then also remove your flag variable.

function reply() {
  socket.emit('Quest' , Quest);
  audio.play();
  // change this to .once()
  socket.once('Ans', function(replyFromBot) {
    console.log("hi");
    var para = document.createElement("p2");
    x = document.getElementById("MiddleBox");
    para.appendChild(document.createTextNode(replyFromBot));
    x.appendChild(para);
    x.scrollTop = x.scrollHeight;
  });
}

Socket.io并不是真正构建为请求/响应系统,而这正是您要使用的系统.更好的方法是使用 socket.io具有的ack功能,因此您可以直接回复发送的Quest消息.

Socket.io is not really built as a request/response system which is what you are trying to use it as. An even better way to implement this would be to use the ack capability that socket.io has so you can get a direct response back to your Quest message you send.

您还需要在服务器上修复共享变量replyFromBotlisten,因为当您有多个用户使用服务器时,它们是并发性问题,请耐心等待.

You also need to fix your shared variables replyFromBot and listen on your server because those are concurrency problems waiting to happen as soon as you have multiple users using your server.

更好的解决方案

一个更好的解决方案是使用socket.io必须具有的ack功能来直接响应您发送的消息.为此,您需要将服务器更改为此:

A better solution would be to use the ack capability that socket.io has to get a direct response to a message you sent. To do that, you'd change your server to this:

function newConnection(socket) {
    console.log(socket.id);
    socket.on('Quest', function(data, fn) {
      let replyFromBot = bot.reply("local-user", data);
      console.log(socket.id+ " "+replyFromBot);
      // send ack response
      fn(replyFromBot);
    });
}

然后,将您的客户端代码更改为此:

And, change your client code to this:

function reply() {
    audio.play();
    socket.emit('Quest', Quest, function(replyFromBot) {
        console.log("hi");
        var para = document.createElement("p2");
        x = document.getElementById("MiddleBox");
        para.appendChild(document.createTextNode(replyFromBot));
        x.appendChild(para);
        x.scrollTop = x.scrollHeight;
    });
}

以这种方式进行操作,您就可以直接从消息中进行回复,因此它作为请求/响应的方式要比处理方式要好得多.

Doing it this way, you're hooking into a direct reply from the message so it works as request/response much better than the way you were doing it.

这篇关于socket.on事件被多次触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆