连接到websocket使webworker在Microsoft边缘无响应

时间:2016-12-22 19:06:03

标签: javascript websocket web-worker

所以这很奇怪,当我尝试连接到websocket 时(这只是一个Microsoft边缘问题)它会在每个第二页刷新webworker时不接受消息{{ 1}}根本不会触发:

考虑以下事项:

main.js

onMessage

webworker.js

    var worker = new Worker("webworker.js");
    worker.postMessage({ type: 'INIT_SOCKET' });

    worker.addEventListener('message',  (event) => {
        let data = event.data;

        if (typeof data === 'string') {
            data = JSON.parse(data);
        }

        if (data.type === 'SOCKET_INITIALIZED') {
            console.log('inititalized');
        }
    });

1 个答案:

答案 0 :(得分:1)

require似乎未在Worker上下文中定义。使用importScripts()将外部脚本导入DedicatedWorkerGlobalScope。例如

importScripts("socket.io.js"); 

无法确定如何停止io()来自轮询和收到错误的调用,可能是由于404错误

socket.io.js:7370 WebSocket connection to 
'ws://echo.websocket.org/socket.io/?EIO=3&transport=websocket' failed:
Error during WebSocket handshake: Unexpected response code: 404

可能是因为对io()的实施方式不熟悉。虽然能够在Socket范围内定义Worker对象。

使用WebSocket的方法返回预期结果

const worker = new Worker("webworker.js");

worker.addEventListener('message', (event) => {
  let data = event.data;

  if (typeof data === 'string') {
    console.log(data)
  }

  if (data.type === 'SOCKET_INITIALIZED') {
    console.log('inititalized');
  }
});

worker.postMessage({
  type: 'INIT_SOCKET'
});

importScripts("socket.io.js");

let sock = io();

console.log(sock); // to demonstrate `Socket` is defined

sock.close(); // closing socket here to prevent `404` polling errors 

self.socket = void 0;

self.onmessage = function(event) {

  var data = event.data;

  console.log('got a event');

  if (typeof data === 'string') {
    data = JSON.parse(data);
  }

  switch (data.type) {
    case 'INIT_SOCKET':
      if (!self.socket) {
        try {

          self.socket = new WebSocket("ws://echo.websocket.org/");

          self.socket.onopen = function(e) {
            socket.send("WebSocket rocks");
            console.log("self.socket event.type:", e.type);
            self.postMessage({
              type: 'SOCKET_INITIALIZED'
            });
          };

          self.socket.onmessage = function(e) {
            console.log(e.data);
            self.socket.close()
          };

          self.socket.onerror = function(e) {
            console.log("self.socket error", e);
          };

          self.socket.onclose = function(e) {
            console.log("self.socket event.type", e.type);
          };

        } catch (e) {
          console.log('some error ', e);
        }

        break;

      };
  }
};

plnkr http://plnkr.co/edit/zVnLE6qG7Kf4yVSb0aJt?p=preview