Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Websocket within Webworker

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
}
like image 590
Jack Avatar asked Aug 01 '13 15:08

Jack


2 Answers

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

socket.onopen = function(){
    // send some message   
};
like image 182
mguimard Avatar answered Nov 15 '22 20:11

mguimard


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;
            }
        }
    }
}
like image 31
Marco Balieiro Avatar answered Nov 15 '22 21:11

Marco Balieiro