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

55 views Asked by At

Docs for the SharedWorker connect event

Docs for the ports property itself

Here's example code which takes a client connection and references a port; this code runs as a SharedWorker (e.g. 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`
  };
  
};

Why is an array of (i.e. potentially a plurality of) ports exposed? When will a SharedWorker ever have more than one port per client, and what would multiple ports represent in such a case? Two different ports connecting the same two agents? (Is there some potential to increase bandwidth at an OS-level by making more ports available??)

The above code ignores all ports other than first - is it always better to use the following instead?

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

There are 0 answers