javascript – Tornado WebSockets – InvalidStateError“仍处于连接状态”

前端之家收集整理的这篇文章主要介绍了javascript – Tornado WebSockets – InvalidStateError“仍处于连接状态”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在写一个web应用程序,我想通过SSL在Tornado WebSockets上从客户端向服务器端发送JSON-Code.当我想建立连接时,Google Chrome会在控制台日志中显示错误

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

我的python服务器看起来像这样:

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,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()

我的客户:

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);
    });
});

谢谢

最佳答案
在连接就绪状态之前,不要让套接字发送数据.

这些功能可能有助于:

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);
    };

猜你在找的Python相关文章