socket.io emits multiple times

后端 未结 3 1666
天命终不由人
天命终不由人 2021-01-04 06:53

I have got a very basic example. This question has been asked previously multiple times in stack overflow itself but I could not get the right answer so I am going with this

相关标签:
3条回答
  • 2021-01-04 07:24

    I think you are adding more and more listeners to 'result' each call you make to check.

    First time click -> call 1 console.log from call 1 listener

    Second time click -> call 1 console.log from call 1 listener + call 2 console.log from call 1 listener + call 2 console.log from call 2 listener

    Third time -> The previous logs + call 3 console.log from call 1 listener + call 3 console.log from call 2 listener and call 3 console.log from call 3 listener.

    Try putting the listener for 'result' out of the function:

    <html>
     <body>
        <button onclick="check()">Test Me :-)</button>
        <script src="/socket.io/socket.io.js"></script>
        <script>
          var socket = io.connect('http://localhost:3000');
    
           socket.on('result', function(data){
                console.log('The data is '+data)
            })
          var check = function(){
    
            var data = { id : '234'};
            socket.emit('chat', data);
          }
        </script>
     </body>
    </html>
    
    0 讨论(0)
  • 2021-01-04 07:29

    I didn't read the question, but I'm putting this on here to help the others, cause I hadn't find this kind of answer yet.

    In my case, I was calling the function next multiple times, just like so

    io.use(async (socket, next) => {
        let req = socket.request
        let res = req.res || {}
    
        someMiddleware()(req, res, next)
        anotherMiddleware({extended: false})(req, res, next)
        anotherMiddleware()(req, res, next)
        anotherMiddleware(req, res, next)
        anotherMiddleware()(req, res, next)
        anotherMiddleware()(req, res, next)
    })
    

    Every time I was calling a middleware, the next function was getting called and on('connection') was being called too. What I got to do was overwrite the next and put it inside the last middleware, so connection get called just once.

    . . .
    let originalNext = next
    next = () => {} // NOW its not going to annoy anymore
    someMiddleware()(req, res, next)
    anotherMiddleware({extended: false})(req, res, next)
    anotherMiddleware()(req, res, next)
    anotherMiddleware(req, res, next)
    anotherMiddleware()(req, res, next)
    anotherMiddleware()(req, res, originalNext) //next get called <
    . . . 
    
    0 讨论(0)
  • 2021-01-04 07:33

    For the Client Side you can use socket.once() instead of socket.on() Ex -

    socket.once('result', function(data){
     console.log('The data is '+data)
    })
    
    0 讨论(0)
提交回复
热议问题