【问题标题】:Socket is emiting too many times, can't close it Angular套接字发射太多次,无法关闭它
【发布时间】:2019-06-18 12:36:38
【问题描述】:

我正在尝试使用 socket.io 在我网站上的聊天模块中的用户之间发送消息。

消息通过正常,但行为很奇怪,它来自我将 socket.io 的 jquery 文档翻译成 javascript 的方式。

第一个发送一次。 第二个很好。 第三次两次。 第四次三遍。 等等。

例如,如果我输入:foo, void, int, double,则会显示:

富

无效

无效

int

int

int

双倍

双倍

双倍

双倍

到目前为止,这是我的代码:

html:

<form action="" [formGroup]="messageForm" (ngSubmit)="sendMessage()">
  <input id="message" formControlName="message" #message class="form-control" class="messageInput" autocomplete="off"/>
  <button type="submit" class="btn btn-primary btn-lg btn-block">SEND</button>
</form>

sendMessage() called from html:

sendMessage() {
  if (this.messageForm.valid) {
    this.message = this.messageForm.get('message').value;
    this.messageForm.reset();
    this.socket.emit('chat message', this.message);
    this.socket.on('chat message', this.receive);
  }
}

receive = function(msg) {
  console.log('receive called'); // called incrementally over time, 1, 22, 333 etc..
  const li = document.createElement('li');
  document.getElementById('messageList').appendChild(li);
  li.innerHTML = msg;
};

backend:

io.on('connection', function(socket){
    socket.on('disconnect', function(){
    });
   socket.on('chat message', function(msg){
        io.emit('chat message', msg);
   });
 });

Here is the socket.io tutorial code for reference:

$(function () {
    var socket = io();
    $('form').submit(function(e){
        e.preventDefault(); // prevents page reloading
        socket.emit('chat message', $('#m').val());
        $('#m').val('');
         return false;
    });
    socket.on('chat message', function(msg){
        $('#messages').append($('<li>').text(msg));
    });
});

在做了一些研究和“console.logging”之后,看起来receive() 被以指数方式调用,一次是第一条消息,两次是第二条消息等等。我相信我错过了对@987654331 的正确翻译@从socket.io jquery的代码到我的Angular改编中..

我能做什么?

【问题讨论】:

  • 有人可以帮忙吗? :)

标签: angular socket.io


【解决方案1】:

知道了!

this.socket.on('chat message', this.receive); 不应在 sendMessage() 函数内。它存在于要声明一次的套接字初始化中:

try {
    this.socket = io.connect('http://localhost:3000');
    this.socket.on('chat message', this.receive);
  } catch (e) {
      console.log('Could not connect socket.io');
  }

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 2011-08-01
    • 2016-04-24
    相关资源
    最近更新 更多