本文介绍了Webworker 中的 HTML5 Websocket的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

推荐答案

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

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

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

这篇关于Webworker 中的 HTML5 Websocket的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 02:05