原创

P2P通信 - WebRTC实现文件实时传输

项目地址:https://github.com/phpisfuture/webrtc-web-android-ios-video-chat-demo

原理

使用RTCPeerConnection对象的channel传输数据(不了解可以点击先了解turn服务channel数据传输),并使用ondatachannel、onmessage、onopen、onclose事件对数据进行处理,传送时候要指定数据文件信息。

核心代码

// 创建channel
dc = pc.createDataChannel('chatchannel');
dc.onmessage = receivemsg;
dc.onopen = dataChannelStateChange;
dc.onclose = dataChannelStateChange;

// 发送数据:
function handleFileInputChange() {
    var file = fileInput.files[0];
    if (!file) {
        console.log('No file chosen');
    } else {
        fileName = file.name;
        fileSize = file.size;
        fileType = file.type;
        lastModifyTime = file.lastModified;

        sendMessage(roomid, {
            type: 'fileinfo',
            name: file.name,
            size: file.size,
            filetype: file.type,
            lastmodify: file.lastModified
        });

        btnSendFile.disabled = false;
        sendProgress.value = 0;
        receiveProgress.value = 0;

        receiveBuffer = [];
        receivedSize = 0;
    }
}

// 接收数据
function receivemsg(e){

    console.log(`Received Message ${e.data.byteLength}`);
    receiveBuffer.push(e.data);
    receivedSize += e.data.byteLength;

    receiveProgress.value = receivedSize;

    if (receivedSize === fileSize) {
        var received = new Blob(receiveBuffer);
        receiveBuffer = [];

        downloadAnchor.href = URL.createObjectURL(received);
        downloadAnchor.download = fileName;
        downloadAnchor.textContent =
            `Click to download '${fileName}' (${fileSize} bytes)`;
        downloadAnchor.style.display = 'block';
    }
}
正文到此结束
本文目录