joewalnes / reconnecting-websocket

A small decorator for the JavaScript WebSocket API that automatically reconnects
MIT License
4.21k stars 970 forks source link

Wait for websocket connection to send a message #98

Open fabioDMFerreira opened 6 years ago

fabioDMFerreira commented 6 years ago

I noticed that my application breaks on sending a message while websocket still be connecting to the server. This can be handled in application side, but I think it would be good to have some timer or have a queue of messages to send on reconnecting in this library side. This isn't elegant but here it is what I did to solve the problem.

this.send = function (data) {
        if (ws) {
            if (self.debug || ReconnectingWebSocket.debugAll) {
                console.debug('ReconnectingWebSocket', 'send', self.url, data);
            }
            //if socket is connecting wait 500ms to retry send the message
            if(ws.readyState === 0){
                return setTimeout(()=>this.send(data),500);
            }
            return ws.send(data);
        } else {
            throw 'INVALID_STATE_ERR : Pausing to reconnect websocket';
        }
    };
qianlongo commented 6 years ago

@fabioDMFerreira That way may not solve the problem completely. After 500 milliseconds, the WS state may not be 1