Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot reopen websocket after calling $close() #8

Open
gtarcea opened this issue Nov 13, 2014 · 4 comments
Open

Cannot reopen websocket after calling $close() #8

gtarcea opened this issue Nov 13, 2014 · 4 comments

Comments

@gtarcea
Copy link

gtarcea commented Nov 13, 2014

ng-websocket will not allow you to re-open a websocket if you have called $close() on it. After working through the code I've found the problem is in the function $websocketService line 68:
if (typeof ws === 'undefined') {

If the socket was previously opened and then closed, then wss.$get() will return the ws that was closed, so ws is not equal to 'undefined' and it never actually trys to create a new WebSocket. I changed line 68 to:
if (typeof ws === 'undefined' || ws.$status() === ws.$CLOSING || ws.$status() === ws.$CLOSED) {

I can send a pull request if required.

@wilk
Copy link
Owner

wilk commented Dec 14, 2014

Hi @gtarcea!
Sorry for this delay.
Well, I tried the following example and it worked:

angular.controller('MyCtrl', ['$websocket', function ($websocket) {
        var ws = $websocket.$new({
            url: 'ws://localhost:12345',
            mock: true
        });

        var count = 0;

        ws.$on('$open', function () {
            if (count === 0) ws.$close();
            count++;
        });

        ws.$on('$close', function () {
            ws.$open();
        });
}]);

When the ws is opened, it closes, just once.
Maybe you expected to re-open the connection via $websocket.$new, did you? If so it's right not to create a new connection because there's a method ($open) that can do it for you.

@martin-langhoff
Copy link

Could this be noted in the documentation? After a few reads of the docs, I ended up making the same mistake as the original posted of this bug report. Only finding the bug report clarified things for me...

thanks! :-)

@wolever
Copy link

wolever commented Jan 5, 2016

+1 — it's very surprising that $websocket.$new can return a closed websocket (and, in fact, also quite surprising that it $new will re-use existing sockets).

@wolever
Copy link

wolever commented Jan 5, 2016

My fix has been monkeypatching $websocket.$get so it always returns undefined:

$websocket.$get = function() { return undefined; }

Ofc this isn't entirely backwards compatible… but also works around this otherwise remarkable behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants