Skip to content

Transport modes

Osra supports two different transport modes:

These two different modes exists because depending on the transport you want to use, the platform allows us to send the data more efficiently.

If you were to transfer an image from your web page to a web worker, calling postMessage() with the transfer option would allow us to transfer that data instead of copying it, like so:

main.ts
const
const worker: Worker
worker
= new
var Worker: new (scriptURL: string | URL, options?: WorkerOptions) => Worker

The Worker interface of the Web Workers API represents a background task that can be created via script, which can send messages back to its creator.

MDN Reference

Worker
('/worker.ts', {
WorkerOptions.type?: WorkerType | undefined
type
: 'module' })
const
const buffer: ArrayBuffer
buffer
= new
var ArrayBuffer: ArrayBufferConstructor
new (byteLength: number, options?: {
maxByteLength?: number;
}) => ArrayBuffer (+2 overloads)
ArrayBuffer
(1024)
const worker: Worker
worker
.
Worker.postMessage(message: any, options?: StructuredSerializeOptions): void (+1 overload)

The postMessage() method of the Worker interface sends a message to the worker. The first parameter is the data to send to the worker. The data may be any JavaScript object that can be handled by the structured clone algorithm.

MDN Reference

postMessage
(
const buffer: ArrayBuffer
buffer
, {
StructuredSerializeOptions.transfer?: Transferable[] | undefined
transfer
: [
const buffer: ArrayBuffer
buffer
] })

This is only possible when the two peers can share the same memory space(the browser’s) and those transports are what we call “Structured” transports like the Worker, SharedWorker, and more.

The other type of transport are called “JSON” transports, which includes WebSocket and WebExtension’s Port.

Osra will automatically choose the appropriate transport mode for you depending on your transport, so you generally don’t have to worry about it. For cases where you are out of osra’s default scope, you can always specify the transport mode manually through osra’s Custom Transport.