socket io emit failed callback
Asked Answered
R

1

9

Is there any way to know socket io emit failed and success, something like ajax callback methods: onSuccess, onError? For socket io emit i only find:

socket.emit('publish', {message:'test message'},function (data) { alert("")})

This callback only be called when the server send an ack response.But it can not apply for this situation:

At the moment of emit message to server, there is bad network or lost connection, that means server not receive this message, so the client callback function is not called.

What I want is:

When I call the socket io emit, if it fails, I want to retry 3 times.

Relationship answered 25/12, 2015 at 2:31 Comment(2)
If you want to imitate HTTP behaviour you'd have to write that mechanism yourself, as it's not part of the websocket's job. But it can be done pretty easily with setTimeout and a few flags.Tman
Have you tried using 'error' event callback ?Savage
M
0

I know this is an old post, but just in case anyone is still having trouble with this.

var socket = new io.connect('http://localhost:3000', {
    'reconnection': true,
    'reconnectionDelay': 1000,
    'reconnectionDelayMax' : 5000,
    'reconnectionAttempts': 3
});
socket.on('connect_error', function() {
    console.log('Connection failed');
});
socket.on('reconnect_failed', function() {
    // fired only after the 3 attemps in this example fail
    console.log('Reconnection failed');
});

More info here -> https://socket.io/docs/client-api/#manager-reconnectionAttempts-value

Melchior answered 7/6, 2020 at 20:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.