javascript Webworker 中的 HTML5 Websocket

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17998011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:23:59  来源:igfitidea点击:

HTML5 Websocket within Webworker

javascriptwebsocketweb-worker

提问by Hyman

I've managed to get websockets working inside a webworker using Chrome, but only for receiving data. When I try to send data I get a DOM Exception, has anyone managed to send data?

我已经设法让 websockets 在使用 Chrome 的 webworker 中工作,但仅用于接收数据。当我尝试发送数据时出现 DOM 异常,是否有人设法发送数据?

This is what I have for my web worker.

这就是我为我的网络工作者所拥有的。

self.addEventListener('message', function(e) {
var data = e.data;

switch (data.cmd) {
    case 'init':
        self.postMessage("Initialising Web Workers...");
        testWS();
        break;
    default:
        self.postMessage('Unknown command: ' + data.msg);
    };
}, false);

function testWS() {
    var connectionAddr = "ws://localhost:8003";
    var socket = new WebSocket(connectionAddr);
    socket.onmessage = function(event) {
        self.postMessage('Websocket : ' + event.data);
    };

    socket.onclose = function(event) {
    };

    function send(message) {
        socket.send(message);
    }

    send("hello"); //Here is where the exception is thrown
}

回答by mguimard

You must listen for the onopen websocket event before sending your first message.

在发送第一条消息之前,您必须监听 onopen websocket 事件。

socket.onopen = function(){
    // send some message   
};

回答by Marco Balieiro

Try this:

试试这个:

var WebSocketStateEnum = {CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3};

var wsChannel;
var msgQueue = [];

// Using like this:
sendMessage(_ => {
    wsChannel.send('message...'); // This will wait until the connection open, unless it is already opened
});

function sendMessage(task) {
    if (!wsChannel || wsChannel.readyState != WebSocketStateEnum.OPEN) {
        msgQueue.push(task);
    } else {
        task();
    }

    if (!wsChannel) {
        wsChannel = new WebSocket('ws://your-url');
        wsChannel.onopen = function() {
            while (msgQueue.length > 0) {
                msgQueue.shift()();
            }
        }
        wsChannel.onmessage = function(evt) {
            // message received here
        }

        wsChannel.onclose = function(evt) {
            wsChannel = null;
        }

        wsChannel.onerror = function(evt) {
            if (wsChannel.readyState == WebSocketStateEnum.OPEN) {
                wsChannel.close();
            } else {
                wsChannel = null;
            }
        }
    }
}