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

后端 未结 3 1233
情深已故
情深已故 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:20

    You should use the callback parameter while defining the event handler.

    A typical implementation would be as follows:

    Client side

    var socket = io.connect('http://localhost');
    socket.emit('set', 'is_it_ok', function (response) {
        console.log(response);
    });
    

    Server side

    io.sockets.on('connection', function (socket) {
        socket.on('set', function (status, callback) {
            console.log(status);
            callback('ok');
        });
    });
    

    Now check the console on the server side. It should display 'is_it_ok'. Next check console on client side. It should display 'ok'. That's the confirmation message.

    Update

    A socket.io connection is essentially persistent. The following in-built functions let you take action based on the state of the connection.

    socket.on('disconnect', function() {} ); // wait for reconnect
    socket.on('reconnect', function() {} ); // connection restored  
    socket.on('reconnecting', function(nextRetry) {} ); //trying to reconnect
    socket.on('reconnect_failed', function() { console.log("Reconnect failed"); });
    

    Using the callback option shown above is effectively a combination of the following two steps:

    socket.emit('callback', 'ok') // happens immediately
    

    and on the client side

    socket.on('callback', function(data) {
        console.log(data);
    });
    

    So you don't need to use a timer. The callback runs immediately except if the connection has any of the following states - 'disconnect', 'reconnecting', 'reconnect_failed'.

提交回复
热议问题