Websocket挂在握手上从Javascript客户端到Python服务器

时间:2017-12-21 22:49:20

标签: javascript python websocket

我有一个javascript客户端试图将一些数据发送到python websocket服务器,并且它一直挂在握手上。这是javascript代码:

function sendData(data)
{ 
    document.getElementById('demo').innerHTML = data;
    var connection = new WebSocket('ws://localhost:10024');
    console.log(data.byteLength)
    try
    {
        connection.onopen = function ()
        {
            console.log("Attempting connection...")    
        }
        connection.onerror = function(error)
        {
            console.log("Error: " + error);
        }
        connection.onmessage = function (e) 
        {
            console.log("Server: " + e.data)
        }

        while(connection.readyState == WebSocket.CONNECTING)
        {
            console.log("Still connecting...")
        }

        if(connection.readyState == WebSocket.OPEN)
        {
            console.log("Connected succesfully!");

            for(var i = 0; i < data.byteLength; i*=256)
            {
                // a 256 byte chunk of the datafile
                var dataChunk = data.slice(i, i+256);
                connection.send(dataChunk);
                //console.log(dataChunk)
                console.log("Sending chunk: " + i + " bytes to " + (i+256) + "bytes");
            }
        }
    }
    catch(ex)
    {
        console.log("Exception: " + ex)
    }
}

我正在尝试发送的数据正在成功加载,因为我检查了此函数的内部和内部。问题是“仍在连接......”。消息被打印数千次。如果你中断连接或尝试发送数据而不检查readyState,它会告诉我它无法连接,因为它仍处于连接过程中,这让我相信这个过程的握手部分存在一些问题。

这是Python服务器:

async def write_plain_file(websocket, path):
    index = 1
    file = open('received_'+str(index)+".jpg", 'wb')
    print("Waiting to receive some data...")
    while True:
        # we receive a generator of the data sent through
        dataChunkGen = await websocket.recv()
        print("Chunk received!");
        # we extract the data from the generator
        dataChunk = next(dataChunkGen)
        file.write(dataChunk)


start_server = websockets.serve(write_plain_file, 'localhost', '10024')

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
print("session is finished")

由于握手永远不会完成,它挂在await websocket.recv()上。我是否需要手动发送回服务器的部分握手?我将如何实现这一目标?

编辑: 这里是正确的代码,事实证明我一直在以错误的方式进行调查,需要轮询,而不是像/ u / Xufox建议的那样循环。代码来自此处:How to wait for a WebSocket's readyState to change

function sendMessage(msg, ws){
    // Wait until the state of the socket is not ready and send the message when it is...
    waitForSocketConnection(ws, function(){
        console.log("message sent!!!");
        ws.send(msg);
    });
}

// Make the function wait until the connection is made...
function waitForSocketConnection(socket, callback){
    setTimeout(
        function () {
            if (socket.readyState === 1) {
                console.log("Connection is made")
                if(callback != null){
                    callback();
                }
                return;

            } else {
                console.log("wait for connection...")
                waitForSocketConnection(socket, callback);
            }

        }, 5); // wait 5 milisecond for the connection...
}


/* Using websockets we connect to the SSL server and send the data through */
function sendData(data)
{ 
    document.getElementById('demo').innerHTML = data;
    var connection = new WebSocket('ws://localhost:10024');
    console.log(data.byteLength)
    try
    {
        connection.onopen = function ()
        {
            console.log("Attempting connection...")    
        }
        connection.onerror = function(error)
        {
            console.log("Error: " + error);
        }
        connection.onmessage = function (e) 
        {
            console.log("Server: " + e.data)
        }

        sendMessage(data, connection)
    }
    catch(ex)
    {
        console.log("Exception: " + ex)
    }
}

和更新的python服务器:

async def write_plain_file(websocket, path):
    index = 1
    file = open('received_'+str(index)+".jpg", 'wb')
    print("Waiting to receive some data...")
    while True:
        # we receive a generator of the data sent through
        dataChunk = await websocket.recv()
        print("Chunk received!");
        # we extract the data from the generator
        print(dataChunk)
        file.write(dataChunk)


start_server = websockets.serve(write_plain_file, 'localhost', '10024', subprotocols='wamp')

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
print("session is finished")

0 个答案:

没有答案