Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tornado WebSockets - InvalidStateError "Still in CONNECTING State"

I am writing on a web-application where I want to send JSON-Code from the client-side to the server-side over Tornado WebSockets with SSL. When I want to build a connection, Google Chrome shows in the console-log the error:

Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING State. 

My python server looks like this:

from tornado import websocket, web, ioloop
import json
from sqlite3functions import *


class SocketHandler(websocket.WebSocketHandler):
    def on_message(self, message):
        handleRequest(self, json.loads(message), True)
        print(message)

    def handleRequest(obj, message, isWebsock):
        ...


    def writeResponse(obj, message, isWebsock):
        if (isWebsock):
            obj.write_message(message)
        else:
            print(message)
            obj.write(message)
            print('msg sent')

app = web.Application([
  (r'/w', SocketHandler)
])

if __name__ == "__main__":
  app.listen(8888)
  ioloop.IOLoop.instance().start()

My client:

var ws;

function connect() {
 ws = new WebSocket('wss://127.0.0.1:8888/w');
 ws.onopen = function()
 {
   ws.send("Message to send");

 };                     
}


$(document).ready(function() {  
    connect();

    $("#Button").on('click', function() {
        ...      
        ws.send(data);
    });
});

Thanks

like image 920
user3086983 Avatar asked Sep 30 '22 16:09

user3086983


1 Answers

Don't let your socket send data until its ready state is connected.

These functions may help:

function sendMessage(msg) {
        waitForSocketConnection(nvWS, function() {
            ws.send(msg);
        });
    };


function waitForSocketConnection(socket, callback){
        setTimeout(
            function(){
                if (socket.readyState === 1) {
                    if(callback !== undefined){
                        callback();
                    }
                    return;
                } else {
                    waitForSocketConnection(socket,callback);
                }
            }, 5);
    };
like image 164
Benjamin Trent Avatar answered Oct 15 '22 09:10

Benjamin Trent