WebRTC is an open-source project that allows web applications to transfer data peer-to-peer. In this post, you will learn how to use the WebRTC API methods to transfer data peer-to-peer.
To create a connection between a local peer and a remote, you can use The RTCPeerConnection interface. It provides methods to connect, maintain, and monitor the connection and close the connection to a remote peer.
One of the main options to create a connection is the iceServers. The URL’s property specifies the URL of the server to be used for ICE negotiations. These STUN servers are used to discover between each peer its public IP and port, and then pass the public IP on to another peer. The TURN servers are used to relay traffic if the connection peer-to-peer fails
You can create a network channel between the peers when the connection between the peers is established.
According to Code Reference #2, each peerConnection will create a channel by calling the method createDataChannel and you will need to set the binaryType property as arraybuffer. On the other side, it must implement the ondatachannel event handler to process the data sent as you can see in the next Code Reference #3.
The file transfer has a problem when it needs to send a big file because the browser has by default a maximum buffer of 256kB.
One solution for the bigger files is to send small messages through the channel. Therefore, you will use the method arrayBuffer to split the file into an array buffer and it will send a flag to say that it has sent the last file chunk. The file chunks will have a size of 64kB. It also will send the arrayBuffer byteLength through the channel (see code reference #4). Furthermore, it is important to know that all the chunks MUST arrive and in the right order to get the file correctly.
Furthermore, it is important to know that the chunks are sequentially sending and if it will overflow the outgoing channel buffer. So, you will add all chunks to a queue to pop and send each one when the channel buffer is below the threshold specified. To know if the channel buffer is below the threshold, you will use the bufferedamountlow event. In the code reference #6 below, you can see the queue handler and send handler.
The side where it will receive all file chunks will set an array to store the chunks or array buffers. The stop method to know if it has received all file chunks is when the channel gets a Channel.LAST_DATA_OF_FILE value-like message. The next step is to download the file and the final step is to close the channel (see Code Reference #7).
Finally, you will set all chunks into a new array buffer and put the new array buffer into a Blob after it downloads, as you can see in the Code Reference #8.
We’d love to learn more about your project.
Engagements start at $75,000.