Learning WebRTC peer-to-peer communication, part 1

[link VIDEO]

Remember blockchain-redux? Yeah, I’m still working on it. Last time, we got it to share blocks between clients in real-time.

But that still used Firebase as the communication channel. Our blockchain isn’t really distributed. ☹️

I have to fix that before my talk at WeAreDevelopers Congress in Vienna. Otherwise, what’s the point?

WebRTC can do that for us. Get browsers to talk to each other without any servers at all.

I built a demo app that uses RTCPeerConnection to build a peer-to-peer connection with itself. You can see the code on GitHub or keep reading.

Got same page WebRTC working o/

Now how do I peer-to-peer pic.twitter.com/kHTPrmpJp5

— Swizec (@Swizec) May 6, 2018

Since iOS 11, WebRTC now works in all browsers people use. You can use it for real!

Try my demo here. I’d embed an iframe, but browser security rules say no.

WebRTC offers 3 APIs:

In this article, we’ll use 2 of them. Media and peer connection.

RTCPeerConnection connects clients without servers

RTCPeerConnection process sketch

RTCPeerConnection process sketch

You establish a connection between 2 clients on the same page like this

  1. Instantiate two RTCPeerConnection objects
  2. Add each other as ICE candidates
  3. createOffer on the 1st object
  4. set local/remote “description” on both
  5. createAnswer on the 2nd object
  6. set remote/local “description” on both
  7. Enjoy your direct communication

Here’s how that goes in code.

We start with a React component that renders 2 videos and 3 buttons. It has a bunch of default state that we’ll use to drive everything.

class WebRTCPeerConnection extends React.Component {
    state = {
        startDisabled: false,
        callDisabled: true,
        hangUpDisabled: true,
        servers: null,
        pc1: null,
        pc2: null,
        localStream: null
    };
 
    localVideoRef = React.createRef();
    remoteVideoRef = React.createRef();
 
    start = () => {
        // start media devices
    };
 
    call = () => {
        // initiate a call
    };
 
    hangUp = () => {
        // hang up connection
    };
 
    render() {
        const { startDisabled, callDisabled, hangUpDisabled } = this.state;
 
        return (
            

class WebRTCPeerConnection extends React.Component { state = { startDisabled: false, callDisabled: true, hangUpDisabled: true, servers: null, pc1: null, pc2: null, localStream: null }; localVideoRef = React.createRef(); remoteVideoRef = React.createRef(); start = () => { // start media devices }; call = () => { // initiate a call }; hangUp = () => { // hang up connection }; render() { const { startDisabled, callDisabled, hangUpDisabled } = this.state; return (

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

This site uses Akismet to reduce spam. Learn how your comment data is processed.

TOP