How to be sure that message via socket.io has been received to the client?

后端 未结 3 1230
情深已故
情深已故 2020-12-24 08:03

How to check that message sent with socket.io library has been received to the client. Is there special method for it in socket.io?

Thanks for you

3条回答
  •  独厮守ぢ
    2020-12-24 08:22

    You can use the socket.io's acknowledgements.

    Quote from the socket.io documentation:

    Sometimes, you might want to get a callback when the client confirmed the message reception.

    To do this, simply pass a function as the last parameter of .send or .emit. What's more, when you use .emit, the acknowledgement is done by you, which means you can also pass data along.

    On the client side simply emit the event with your data, the function will be called whenever the server responds to your event:

    client.emit("someEvent", {property:value}, function (data) {
      if (data.error) 
        console.log('Something went wrong on the server');
    
      if (data.ok)
        console.log('Event was processed successfully');
    });
    

    On the server side you get called with the data and the callback handle to send the response:

    socket.on('someEvent', function (data, callback) {
    
      // do some work with the data
    
      if (err) {
        callback({error:'someErrorCode', msg:'Some message'});
        return;
      }
    
      callback({ok:true});
    });
    

提交回复
热议问题