jrief / django-websocket-redis

Websockets for Django applications using Redis as message queue
http://django-websocket-redis.awesto.com/
MIT License
896 stars 222 forks source link

How to explicitly close the ws4redis connection? #179

Closed yguarata closed 8 years ago

yguarata commented 8 years ago

Hi there,

I have an scenario where I need to close the websocket connection and open it again but in a different channel. However, the ws4redis.js does not expose its websocket connection object (ws). Any ideas on how should I proceed to achieve this?

Thanks in advance!

Tantrisse commented 8 years ago

Hey, Dunno if it's a good way or not but personally I copied "ws4redis.js" into my static/js folder. It make django serve my ws4redis.js I modified to expose all I need (function, callback, ws object...)

I think it's definitively not the best solution so I'm open to any better implementation :)

yguarata commented 8 years ago

Hey @Eirika, thanks for your reply. I have considered to do just as you did, but I would not like to have my own version of ws4redis.js. Maybe we should try to improve the project's javascript API, keeping backwards compatibility, and try some pull requests.

jrief commented 8 years ago

How about adding

    this.close = function() {
        return ws.close();  
    };

to WS4Redis?

If that works, I'll add it to the project.

Tantrisse commented 8 years ago

Personally I had to do :

this.close = function() {
    // Avoid reconnect
    ws.onclose = function() {};
    // Ignore errors cause Chrome throw "bit reserved=1"
    // Probably need to dig why this error appear
    ws.onerror = function() {};
    // Cleat timer Interval to avoid reconnect
    if(timer) {
      clearInterval(timer);
    }
    // Clear heartbeat Interval
    if(heartbeatInterval) {
      clearInterval(heartbeatInterval);
    }
    ws.close();
  };

Please tell me what you think about it :)

yguarata commented 8 years ago

Hi @jrief, first of all thanks for your time! Currently, if we simply call ws.close(), WS4Redis would try to reconnect immediately. We need to flag WS4Redis to inform that a disconnection was intentionally, and thus it should not try to reconnect. Maybe, something like this:

function on_close(evt) {
        console.log("Connection closed!");
        if (must_reconnect && !timer) { // must_reconnect must be set true on initialization
            // try to reconnect
            var interval = generateInteval(attempts);
            timer = setTimeout(function() {
                attempts++;
                connect(ws.url);
            }, interval);
        }
    }

this.close = function() {
    must_reconnect = false;
    return ws.close();  
};
yguarata commented 8 years ago

This is solved by pull request #181, which will be present in the next release (0.4.7).