使用方法
# 快速入门
将以下代码拷贝到您的网页中并运行。再打开另一个相同的网页。见证奇迹的时候到了!您已在两个网页之间建立了一个P2P连接,在不安装任何插件的情况下。如果在这个频道中(一个url标识了一个频道)没有其它参与者,那么您打开的第一个网页将作为种子为第二个网页提供数据。
<script src="https://cdn.jsdelivr.net/npm/cdnbye-file@latest"></script>
<h3>download info:</h3>
<p id="url"></p>
<p id="mime"></p>
<p id="size"></p>
<p id="progress"></p>
<p id="speed"></p>
<p id="p2p"></p>
<script>
var url = 'https://webtorrent.io/torrents/Sintel/Sintel.mp4';
var downloader = new P2PEngineFile(url);
downloader.on('metadata', function (source) {
document.querySelector('#url').innerText = `Url: ${source.getUrl()}`;
document.querySelector('#mime').innerText = `Mime: ${source.getMime()}`;
document.querySelector('#size').innerText = `Size: ${source.getFileLength()}`;
})
.on('finished', function (file) {
document.querySelector('#progress').innerText = `Download finished`
file.save('test.mp4')
})
.on('progress', ratio => {
document.querySelector('#progress').innerText = `Progress: ${ratio.toFixed(2)}%`
})
.on('speed', speed => {
document.querySelector('#speed').innerText = `Speed: ${Math.round(speed/1000)}KB/s`
})
.on('failed', function (e) {
// fallback
var a = document.createElement('a');
a.download = "test.mp4";
a.href = url;
document.body.appendChild(a);
a.click();
a.remove();
})
.on('stats', function (stats) {
var total = stats.totalHTTPDownloaded + stats.totalP2PDownloaded;
document.querySelector('#p2p').innerText = `p2p ratio: ${Math.round(stats.totalP2PDownloaded/total*100)}% saved traffic: ${Math.round(stats.totalP2PDownloaded)}KB upload: ${Math.round(stats.totalP2PUploaded)}KB`;
})
downloader.start();
</script>
# 绑定域名
在使用P2P服务之前,需要先绑定域名。
Localhost (127.0.0.1) 已加入白名单,无需绑定,用于本地调试。
# 准备工作
# 跨域配置
请确保文件服务器已做好跨域配置
# 允许 OPTIONS 请求
OPTIONS 请求是在跨域环境下 RANGE 请求的前置请求,一般情况下可以在 HTTP 响应头中添加:
Access-Control-Allow-Methods: GET, OPTIONS
# 允许 RANGE 请求
本SDK需要用到 RANGE 请求,一般情况下可以在 HTTP 响应头中添加:
Access-Control-Allow-Headers: Range
# 兼容 Firefox
某些浏览器如 Firefox 需要在响应头设置 Access-Control-Expose-Headers 才能获取到文件大小:
Access-Control-Expose-Headers: Content-Length
# 引入插件
# Script标签引入
通过script标签引入最新版本:
<script src="https://cdn.jsdelivr.net/npm/cdnbye-file@latest"></script>
# 文件引入
# Browserify / Webpack
npm install --save cdnbye-file
通过 require 引入cdnbye-file:
var P2PEngineFile = require('cdnbye-file');
或者使用ES6的 import 语法:
import P2PEngineFile from 'cdnbye-file';
# 使用插件
实例化 P2PEngineFile 并将文件下载地址作为参数传入。
var downloader = new P2PEngineFile('path/to/your.file');
downloader.on('finished', function (file) {
file.save('name.file');
file.revokeBlobURL(); // 释放file占用的内存
});
downloader.on('failed', function (e) {
// fallback to normal download
});
downloader.on('progress', function (e) {
// show progress to user
});
downloader.start();
# Electron
本插件同样支持 Electron 平台,只需求将从控制台获取的token等信息传进config中即可,如下所示:
p2pConfig: {
token: YOUR_TOKEN,
appName: YOUR_APP_NAME, // 应用的名称
appId: YOUR_APP_ID, // 需要与控制台输入的保持一致
// Other p2pConfig options if applicable
}