Skip to content

Instantly share code, notes, and snippets.

@blenderskool
Last active January 14, 2024 00:14
Show Gist options
  • Save blenderskool/aa66e7d224ca1fc628167689de8f20e1 to your computer and use it in GitHub Desktop.
Save blenderskool/aa66e7d224ca1fc628167689de8f20e1 to your computer and use it in GitHub Desktop.
/**
* Peer 1 (Sender)
* Peer 2 (Receiver)
* This example has both the peers in the same browser window.
* In a real application, the peers would exchange their signaling data for a proper connection.
* The signaling server part is omitted for simplicity
*/
const peer1 = new SimplePeer({ initiator: true });
const peer2 = new SimplePeer();
/**
* Implementing the WebRTC connection between the nodes
*/
// Share the signalling data of sender with the receivers
peer1.on('signal', data => {
peer2.signal(data);
});
// Share the signalling data of receiver with the sender
peer2.on('signal', data => {
peer1.signal(data);
});
/**
* Connection established, now sender can send files to other peers
*/
peer1.on('connect', () => {
const input = document.getElementById('file-input');
// Event listener on the file input
input.addEventListener('change', () => {
const file = input.files[0];
console.log('Sending', file);
// We convert the file from Blob to ArrayBuffer
file.arrayBuffer()
.then(buffer => {
/**
* A chunkSize (in Bytes) is set here
* I have it set to 16KB
*/
const chunkSize = 16 * 1024;
// Keep chunking, and sending the chunks to the other peer
while(buffer.byteLength) {
const chunk = buffer.slice(0, chunkSize);
buffer = buffer.slice(chunkSize, buffer.byteLength);
// Off goes the chunk!
peer1.send(chunk);
}
// End message to signal that all chunks have been sent
peer1.send('Done!');
});
});
});
/**
* Receiver receives the files
*/
const fileChunks = [];
peer2.on('data', data => {
if (data.toString() === 'Done!') {
// Once, all the chunks are received, combine them to form a Blob
const file = new Blob(fileChunks);
console.log('Received', file);
// Download the received file using downloadjs
download(file, 'test.png');
}
else {
// Keep appending various file chunks
fileChunks.push(data);
}
});
@hypo-thesis
Copy link

This is a brilliant example. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment