Webworker中的HTML5 Websocket

时间:2013-08-01 15:16:38

标签: javascript websocket web-worker

我已经设法使用Chrome在webworker中使用websockets,但仅用于接收数据。当我尝试发送数据时,我得到了一个DOM异常,有没有人设法发送数据?

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

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
}

2 个答案:

答案 0 :(得分:21)

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

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

答案 1 :(得分:0)

尝试一下:

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