Socket.io message event firing multiple times

后端 未结 4 689
囚心锁ツ
囚心锁ツ 2021-01-02 10:11

I was trying to learn node and started creating a mashup with socket.io The message transportation have begin but I have run into some trouble.

The message event is

相关标签:
4条回答
  • 2021-01-02 10:30

    I think this misbehavior is because you are attempting to use one of the handful of built-in/reserved event names "message" as an application-specific message. To confirm, change your event name to "message2" or something else and see if the problem goes away. I believe at least "connect", "disconnect", and "message" are reserved. https://github.com/LearnBoost/socket.io/wiki/Exposed-events

    0 讨论(0)
  • 2021-01-02 10:34

    Restarting the server can be responsible for several identical event listeners on the client side. If the client has not reloaded (restarted) you have to make sure that the old event listeners are deleted on the client side when establishing a new connection. You can do that with

    io.socket.removeAllListeners()
    
    0 讨论(0)
  • 2021-01-02 10:51

    So I had the same problem. The solution is to close all your listeners on the socket.on('disconnect') event, this is what my code looks like -

     socket.on('disconnect', function () {
                    socket.removeAllListeners('send message');
                    socket.removeAllListeners('disconnect');
                    io.removeAllListeners('connection');
                });
    

    Might not need to call it on disconnect, not sure but I do it anyway.

    0 讨论(0)
  • 2021-01-02 10:52

    The whole part of socket.io code has to go outside external.chat function. Socket IO has to bind with the http/app server, you should not handle it within each request.

    the messages are firing the number of times = the sequence of connection of the client

    What essentially happening is, each time a new request arrives you are registering a event handler for message, hence it is fired as many times as the you have accessed chat URL.

    io.socket.on('message', function (data) {...})
    
    0 讨论(0)
提交回复
热议问题