Javascript异步WebSocket

问题描述 投票:0回答:1

我有一台服务器,为websocket提供端点。我在浏览器中使用Javascript将数据发送到websocket中的服务器。

从客户端收到第一条消息后,服务器开始处理数据。在(50-100ms)之后不久,服务器将向客户端发送一些消息。

这是我非常简化的代码:

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me</button>

<script>

var ws = null;

window.onload = function () {
    ws = new WebSocket("ws://localhost/client");
}

function sleep(ms) {
    const date = Date.now();
    let currentDate = null;
    do {
        currentDate = Date.now();
    } while (currentDate - date < ms);
}

function myFunction() {
    var messages = new Array();

    ws.onmessage = function (event) {
        console.debug(event.data);
        messages.push(event.data);
    }

    console.error('1');
    let myData = "CONTENT DOES NOT MATTER";

    console.error('2');
    ws.send(myData);
    console.error('3');

    // polling
    for (let i = 0; i < 50; ++i) {
        if (messages.length > 0) {
            console.warn(messages.pop());
        }
        sleep(100);
    }

    console.error('4');
    return true; /*or false*/
}
</script>

</body>
</html>

问题是,可变消息为空,并且在阻塞/轮询部分未调用ws.onmessage函数。Javascript是否有解决方案,我可以在其中编写阻止代码并在阻止部分内从websocket客户端接收/轮询消息?

我需要这个的原因是,我用服务器的结果确定myFunction的返回值。因此,在从函数返回值之前,我需要消息。

javascript multithreading http asynchronous websocket
1个回答
0
投票

将“ myFunction”的声明放入“ window.onload”事件内。由于您在window.onload事件内声明了ws,因此在onload事件外将其为“ null”。

window.onload = function () {
    ws = new WebSocket("ws://localhost/client");
    
    function sleep(ms) {
        const date = Date.now();
        let currentDate = null;
        do {
            currentDate = Date.now();
        } while (currentDate - date < ms);
    }

    function myFunction() {
        var messages = new Array();

        ws.onmessage = function (event) {
            console.debug(event.data);
            messages.push(event.data);
        }

        console.error('1');
        let myData = "CONTENT DOES NOT MATTER";

        console.error('2');
        ws.send(myData);
        console.error('3');

        // polling
        for (let i = 0; i < 50; ++i) {
            if (messages.length > 0) {
                console.warn(messages.pop());
            }
            sleep(100);
        }

        console.error('4');
        return true; /*or false*/
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.