HTML5 Websocket within Webworker

感情迁移 提交于 2019-11-27 17:48:21

问题


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?

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
}

回答1:


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

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



回答2:


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


来源:https://stackoverflow.com/questions/17998011/html5-websocket-within-webworker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!