Sending and Receiving Binary Data

You have now written all of the foundational logic to send and receive binary data along with a custom JSON payload of metadata for each file sent over a data channel. Let’s set up a sendFile() function that opens a data channel for each file a user wants to send.

To start with, create a function that takes two arguments, peer and payload, and a handful of variables:

 function​ sendFile(peer, payload) {
 const​ { metadata, file } = payload;
 const​ file_channel =
  peer.connection.createDataChannel(​`​${metadata.kind}​-​${metadata.name}​`​);
 const​ chunk = 16 * 1024; ​// 16KiB chunks
 }

The body of the function opens by destructuring metadata and file from payload. As you’ll see, that will simplify ...

Get Programming WebRTC now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.