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
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);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With