Aria2是一个非常成熟的下载程序,基于命令行调用。它也提供上RPC、WebSocket的调用方式。下面我会通过前端WebSocket调用的方式实现一个简单的下载功能

1

  1. 首先下载对应的Aria2可执行文件,并且命令行启动。aria2c默认会监听本地6800端口
aria2c --enable-rpc --rpc-listen-all=true --rpc-allow-origin-all
  1. 前端建立WebSocket连接,地址是:ws://localhost:6800/jsonrpc,具体代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>aria2</title>
</head>
<body>
  <div style="margin-bottom: 32px;">
    <input type="text" id="ipt"> 下载进度:<span id="progress"></span> 下载速度:<span id="speed"></span>
  </div>
  <button id="start">开始下载</button>
  <button id="pause">暂停下载</button>
  <button id="unpause">恢复下载</button>
  <script>
    // Create WebSocket connection.
    const socket = new WebSocket('ws://localhost:6800/jsonrpc');

    // Connection opened
    socket.addEventListener('open', function (event) {
      socket.send('Hello Server!');
      console.log(event)
    });

    let timer = {}
    let gid = ''
    // Listen for messages
    socket.addEventListener('message', function (event) {
      const data = JSON.parse(event.data)
      console.log('Message from server  ', event.data)
      if (data.id === 'tellStatus') {
        const progress = parseInt(Number(data.result.completedLength) / Number(data.result.totalLength) * 100) + '%'
        const speed = parseInt(Number(data.result.downloadSpeed) / 1000) + ' kb/s'
        document.querySelector('#progress').innerHTML = progress
        document.querySelector('#speed').innerHTML = speed
      }
      if (data.method === 'aria2.onDownloadStart') {
        gid = data.params[0].gid
        const jsonData = {
          'jsonrpc':'2.0',
          'id':'tellStatus',
          'method':'aria2.tellStatus',
          'params': [gid]
        }
        if (!timer[gid]) {
          timer[gid] = setInterval(() => {
            socket.send(JSON.stringify(jsonData))
            console.log('发送 tellStatus')
          }, 1000)
        }
      }
      if (data.method === 'aria2.onDownloadComplete') {
        gid = data.params[0].gid
        clearInterval(timer[gid])
        delete timer[gid]
        document.querySelector('#progress').innerHTML = '100%'
        document.querySelector('#speed').innerHTML = '0 kb/s'
      }
    });
    const startBtn = document.querySelector('#start')
    startBtn.addEventListener('click', function () {
      const jsonData = {
        'jsonrpc':'2.0',
        'id':'qwer',
        'method':'aria2.addUri',
        'params': [[ document.querySelector('#ipt').value ]]
      }
      socket.send(JSON.stringify(jsonData))
    })
    const pauseBtn = document.querySelector('#pause')
    const unpauseBtn = document.querySelector('#unpause')
    pauseBtn.addEventListener('click', function () {
      const jsonData = {
        'jsonrpc':'2.0',
        'id':'qwer',
        'method':'aria2.pause',
        'params': [gid]
      }
      socket.send(JSON.stringify(jsonData))
    })
    unpauseBtn.addEventListener('click', function () {
      const jsonData = {
        'jsonrpc':'2.0',
        'id':'qwer',
        'method':'aria2.unpause',
        'params': [gid]
      }
      socket.send(JSON.stringify(jsonData))
    })
  </script>
</body>
</html>
  1. Aria2官方文档:https://aria2.github.io/manual/en/html/index.html