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

查看:109
本文介绍了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 和 express 创建了一个基于服务器的聊天机器人应用程序,但是当我第一次调用 socket.on 时,它被执行一次,第二次它在第三次执行两次三次等等我通过在我的客户端上设置一个标志来解决这个问题,以便它只显示一次.我只是想知道我的代码在逻辑上是否正确我的意思是这是一个好代码吗?因为如果客户第 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 并不是真正构建为请求/响应系统,而这正是您尝试将其用作的.实现这一点的更好方法是使用 ack socket.io 具有的功能,因此您可以直接回复您发送的 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.

更好的解决方案

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

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天全站免登陆