为什么 SharedWorker 不为每个客户端公开 1 个端口?

Why doesn't SharedWorker expose exactly 1 port per client?

提问人:Gershom Maes 提问时间:11/15/2023 最后编辑:Gershom Maes 更新时间:11/15/2023 访问量:17

问:

SharedWorker 连接事件的文档

ports 属性本身的文档

下面是采用客户端连接并引用端口的示例代码;此代码作为 SharedWorker 运行(例如):worker.js

onconnect = evt => {
  
  // Client connection represented by `evt`
  
  const port = evt.ports[0];
  port.onmessage = msg => {
    // Client sent us something, represented by `msg`
    // We can reply with `port.postMessage`
  };
  
};

为什么会公开一个(即可能是多个)端口数组?什么时候每个客户端会有多个端口,在这种情况下,多个端口代表什么?SharedWorker

上面的代码忽略了除第一个端口以外的所有端口 - 使用以下端口总是更好吗?

onconnect = evt => {
  
  // Client connection represented by `evt`
    
  for (const port of evt.ports) {
    
    // For each client port, listen to messages on that port (?)
    port.onmessage = msg => {
      // Client sent us something, represented by `msg`
      // We can reply with `port.postMessage`
    };
    
  }
  
};
JavaScript 端口 共享辅助角色

评论

0赞 Wyck 11/15/2023
文档说,当你创建一个 MessageChannel 时,它有两个端口。创建通道的应用用于向另一端发送消息,端口另一端的应用用于将消息发送回创建者。port1port2
0赞 Gershom Maes 11/17/2023
我相信是用在幕后实现的——似乎只有一个端口出现在(当我运行上面的代码时,一直到现在为止)MessageChannelSharedWorkerSharedWorkerGlobalScopeevt.ports.length1

答: 暂无答案