2

I'm trying to learn to use sockets. I did not find anything about this error, or I'm searching for the wrong keywords. Anyways, I can connect to my socket but when I'm trying to send a message I get this error:

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

$('#send-btn').click(function(){ //use clicks message send button    
        var mymessage = $('#message').val(); //get message text
        var myname = $('#name').val(); //get user name

        if(myname == ""){ //empty name?
            alert("Enter your Name please!");
            return;
        }
        if(mymessage == ""){ //emtpy message?
            alert("Enter Some message Please!");
            return;
        }

        //prepare json data
        var msg = {
        message: mymessage,
        name: myname,
        color : '<?php echo $colours[$user_colour]; ?>'
        };
        //convert and send data to server
        websocket.send('hello');
});

I can't find any information about this error or I'm doing the same error again and searching for the wrong keywords. Anyway I hope some of you guys have an answer on what I can do instead or point me in the right direction.

Michael Doye
  • 8,063
  • 5
  • 40
  • 56
Tommy
  • 667
  • 1
  • 10
  • 25

2 Answers2

3

You call the websocket.send() function too fast.

You should call it when the websocket netstate is valid or ESTABLISHED.

You can try the call via setTimeout (the function that calls the websocket.send method and time).

Unheilig
  • 16,196
  • 193
  • 68
  • 98
1

This is my case when my internet connection is interrupted to resolve this error you must send to socket when ready state is ok:

if (socket.readyState == 1) {
    socket.send ('bal bla'); 
}
Elletlar
  • 3,136
  • 7
  • 32
  • 38
Fad Sel
  • 99
  • 2
  • 6