Uncaught Invalidstateerror: Failed to execute 'send' on 'Websocket'

Asked

Viewed 1,313 times

1

Uncaught Invalidstateerror: Failed to execute 'send' on 'Websocket': Still in CONNECTING state. (index):29 (Anonymous Function)

Code:

function smConnect() {
    ws = new WebSocket('ws://127.0.0.1:1805/');
    delete ws.URL;

    ws.onopen = function(response) {
    };

    ws.onmessage = function(response) {
    };

    ws.onclose = function(response) {
    };

    ws.onerror = function(error) {
    };
}

smConnect();
ws.send('message', 'hi');

What can it be?

1 answer

2


According to the returned message, you are trying to execute the method send before even if the connection has been established.

According to the page of W3.org about WebSockets:

The send(data) method transmits data using the connection. If the attribute readyState is connecting, must cast an exception InvalidStateError.

What you should do is wait for the connection to be made and then run the method send.

You can implement this as follows (credits):

function waitForSocketConnection(socket, callback){
        setTimeout(
            function(){
                if (socket.readyState === 1) {
                    if(callback !== undefined){
                        callback();
                    }
                    return;
                } else {
                    waitForSocketConnection(socket,callback);
                }
            }, 5);
    };

And use it like this:

waitForSocketConnection(ws, function() {
    ws.send('message', 'hi');
}); 

Or just do it at the event onOpen:

ws.onopen = function(response) {
    ws.send('message', 'hi');
};
  • 1

    The timer method smells of gambiarra, I prefer the onopen.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.