HTML5 Websocket within Webworker

后端 未结 2 1899
眼角桃花
眼角桃花 2020-12-16 01:22

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 se

相关标签:
2条回答
  • 2020-12-16 01:37

    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;
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-16 01:43

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

    socket.onopen = function(){
        // send some message   
    };
    
    0 讨论(0)
提交回复
热议问题