Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket'

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?

    
asked by anonymous 19.03.2015 / 23:54

1 answer

2

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

According to the w3.org page on WebSockets :

  

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

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

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 simply do this in the event onOpen :

ws.onopen = function(response) {
    ws.send('message', 'hi');
};
    
20.03.2015 / 03:09