Creating and sharing snapshot using DataChannel

Here is a description of the different steps to take snapshot and exchange it between two users using DataChannel.

Create and register a UserAgent

Check our registration tutorial if needed to create the userAgent and register.

Start call

Check our P2P call tutorial to establish a call.

Side A: Send snapshot request message

Here we send a message to the Side B to request a snapshot and start data transfering process

    call.getContact().sendMessage('ask_snapshot')
        .then((id) => {
            console.log('ask_snapshot message sent', id);
        })
        .catch((err) => {
            console.error('Message sending error:', err);
        });
    

Side B: Listen to the snapshot request message

Here we listen to the Session.contactMessage event and start snapshot handling process.

    connectedSession.on('contactMessage', (message) => {
        if (message.content === 'ask_snapshot') {

            // Take snapshot
            // Sent it back using DataChannel - see next steps
        }
    });
    

Side B: Take snapshot

Take snapshot data using canvas element as a buffer:

    let canvas = document.querySelector("#canvas");
    let video = document.querySelector("#localStream video");
    canvas.getContext('2d').drawImage(video, 0, 0);
    

Side B: Start snapshot data transfer back

It sends an invitation to the Side A for creating a data channel:

    let contact = call.getContact();
    dataChannel = contact.startDataChannel();
    

Add DataChannel events listeners:

    dataChannel.on('opened', () => {
        // Channel is ready we can start data transfer
        let base64 = canvas.toDataURL('image/jpeg');
        dataChannel.sendData(base64)
            .then((info) => {
                console.log('Data sent', info);
            })
            .catch((err) => {
                console.error('Data sending error', err);
            });
    }
    

Side A: Handle data channel invitation

Here we listen to Session.dataChannelInvitation event and accept it. Then we start listening to DataChannel.dataReceived event to handle incoming data.

    connectedSession.on('dataChannelInvitation', (invitation) => {
        invitation.accept()
            .then((channel) => {
                dataChannel = channel;
                dataChannel.on('dataReceived', (data) => {
                    console.log('New data', data);
                });
            });
    })
    

You can also subscribe to the other DataChannel and ReceivedDataChannelInvitation events to be informed about transfer progress, invitation status etc.

Live Demo