0

I am getting an error about:

Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. Is there an event I can check to make sure the socket is fully connected before I can send a message.

My code is as follows:

        this.contextWS = new WebSocket(socketAddress);

        this.contextWS.onopen = () => {
            console.log('Websocket is open !!!');
            this.contextWS.send('payload');
        }

Am I making an obvious mistake here?

reza
  • 5,972
  • 15
  • 84
  • 126

1 Answers1

1

After the MDN - WebSocket description:

An event listener to be called when the WebSocket connection's readyState changes to OPEN; this indicates that the connection is ready to send and receive data. The event is a simple one with the name "open".

I'd use onerror event handler to check if there are no errors on the way..

contextWS.onerror = function (event) {
   console.log(event.data);
};

... and onclose event handler to check the reason of unexpectedly closed connections:

contextWS.onclose = function(event) {
      if (event.code == 1000) {
        console.log('WebSocket closed normally');
      } else {
          console.log('WebSocket closed unexpectedly: ' + event.code);
      }

Here's the list of all possible result codes - MDN CloseEvent

You can try to queue your messages and send them when the readyState == 1. Please see the answer from the similar question - proxy function

Mateusz Kleinert
  • 1,316
  • 11
  • 20
  • Thanks for the reply, I read the MDN also. I am still not sure how to make sure the websocket is fully connected. I see the onopen event getting fired and I attempt to send a message and that is when I see the error. The only other events are see are onerror and onclose. Neither sees to be what I need – reza May 22 '17 at 22:11
  • onopen event handler seems to be the right place to go. I've always been using WebSockets this way. Could you please update your example code and add the send() function? – Mateusz Kleinert May 22 '17 at 22:21
  • I've updated the answer. There is a link to the similar question. The described approach seems to be reasonable. Anyway, onopen should work as the documentation say the readyState == OPEN when the event occurs. I've seen a few people saying that onopen is sometimes called twice - once for the readyState == 0 and once for the readyState == 1. Could you please print out the readyState inside your onopen handler? I'm curious if this behaviour really occurs. – Mateusz Kleinert May 22 '17 at 22:40
  • I am seeing the websocket getting closed right away, so that is the core problem. Thank you for pointing me in the correct direction. – reza May 23 '17 at 18:04