MessagePort transport
MessagePortTransport wraps a browser MessagePort and exposes it as a dnet transport.
It is useful when you need a dedicated channel between two JavaScript contexts, such as:
- two sides of a
MessageChannel, - a page and an iframe,
- a page and a worker when the port is passed with
postMessage(), - or any other API that uses
MessagePort.
Constructors:
MessagePortTransport::new(port, codec).awaitcreates a transport over the givenMessagePort.MessagePortTransport::new_with_name(port, codec, name).awaitcreates a named transport.
Note
The underlying
MessagePortis started automatically and the transport waits for the peer side to open before returning.
Multiple named transports can coexist on the same MessagePort, and they can be used at the same time as an unnamed transport on that port.
This makes it easy to multiplex several logical channels over the same underlying port pair.
If you only need a direct worker-host channel, prefer WebWorkerTransport.
If you need to send transferable objects across the port, see the Transferable transport section.
Example
Create a MessageChannel, then wrap each port with MessagePortTransport.
use futures::SinkExt;
use web_sys::MessageChannel;
use dnet::{codecs::BincodeCodec, message_port::MessagePortTransport, Receive};
let channel = MessageChannel::new().unwrap();
let port1 = channel.port1();
let port2 = channel.port2();
let mut left = MessagePortTransport::new(port1, BincodeCodec::default()).await?;
left.send("hello from left".to_string()).await?;
// pass the other port to another context, or just use it in the same context:
let mut right = MessagePortTransport::new(port2, BincodeCodec::default()).await?;
let reply: String = right.receive().await?;
right.send(format!("hello from right, got: {}", reply)).await?;