简体   繁体   English

w.angular在socket.io中重复

[英]duplicates in socket.io w/ angular

Using angular and socket.io I am getting duplicate events on the client everytime the server emits. 使用angular和socket.io,每次服务器发出时,我都会在客户端上得到重复的事件。 Angular is only included once, there is only one socket.io connection, and there is only one listener per event on the client. Angular仅包含一次,只有一个socket.io连接,并且客户端上每个事件只有一个侦听器。 Upon receiving an event on the server, data is logged, and this process only ever happens once. 在服务器上收到事件后,将记录数据,并且此过程仅发生一次。 Then the data is emitted and the callback is called twice on the client, despite only being in scope once(to my knowledge). 然后发出数据,并在客户端上两次调用该回调,尽管仅在作用域内一次(据我所知)。

client:
//inside a controller
var thing ='foo';
socket.emit('sentUp',thing)

socket.on('sentDown',function(thing){
    console.log(thing)//this happens twice
});

server:
/*
node&express stuff here
*/
socket.on('connection',function(socket){
    socket.on('sentUp',function(stuff){
        console.log('this happened')//x1
        socket.emit('sendDown',stuff);
    });
})

Most likely your controllers are being loaded more than once. 您的控制器很可能被多次加载。 You can easily check it by logging. 您可以通过登录轻松检查它。

Move out the socket code from the controllers and put them in a service where they're only called once. 从控制器中移出套接字代码,并将其放入仅被调用一次的服务中。

I have found in my own socket.io client code that some of the connect events can occur each time the client reconnects. 我在自己的socket.io客户端代码中发现,每次客户端重新连接时都会发生一些连接事件。 So, if the connected is lost for any reason and then the client automatically reconnects, the client may get a connect event again. 因此,如果由于任何原因失去了连接,然后客户端自动重新连接,则客户端可能会再次获得连接事件。

If, like me, you're adding your event handlers in the 'connect' event, then you may be accidentially adding multiple event handlers for the same event and thus you would think you were seeing duplicate data. 如果像我一样,在'connect'事件中添加事件处理程序,那么您可能会意外地为同一事件添加多个事件处理程序,因此您会认为自己看到的是重复数据。 You don't show that part of your client code so I don't know you're doing it that way, but this is an issue that hit me and it is a natural way to do things. 您没有显示客户代码的那部分,所以我不知道您这样做的方式,但这是一个困扰我的问题,这是一种自然的处理方式。

If that is what is happening to you, there are a couple possible work-arounds: 如果这是发生在您身上的事情,则有两种可能的解决方法:

  1. You can add your event handlers outside the connect event. 您可以在connect事件之外添加事件处理程序。 You don't have to wait for connection to finish before adding event handlers. 在添加事件处理程序之前,您不必等待连接完成。 This way, you'd only ever do them once. 这样,您将只做一次。

  2. Before adding the event handlers you add upon connection, you can remove any previous event handlers that were installed upon connection to make sure you never get dups. 在添加在连接时添加的事件处理程序之前,您可以删除在连接时安装的所有以前的事件处理程序,以确保您永远不会傻瓜。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM