实现原理
利用Aria2c的json-rpc接口
c# 用 ClientWebSocket 类 连接 Aria2c的json-rpc接口
最后根据Aria2c的json-rpc接口定义发送消息给Aria2
Aria2c的json-rpc接口定义详细信息请看
https://aria2.github.io/manual/en/html/aria2c.html#rpc-interface
这里只有Aria2c定义的类和方法
使用的时候只要先连接Aria2服务器再调用方法就可以了
下面是Aria2c.cs文件的代码
清根据实际情况更改
using System;
using System.IO;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Threading;
using System.Text.RegularExpressions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Aria2详细信息请看
//https://aria2.github.io/manual/en/html/aria2c.html#rpc-interface
namespace aria2c
{
//定义一个类用于转码成JSON字符串发送给Aria2 json-rpc接口
public class JsonClass
{
public String _jsonrpc { get; set; }
public String _id { get; set; }
public String _method { get; set; }
public List<String> _params { get; set; }
}
public class Aria2
{
public static ClientWebSocket webSocket; //用于连接到Aria2Rpc的客户端
public static CancellationToken cancellationToken; //传播有关应取消操作的通知
/// <summary>
/// 连接Aria2Rpc服务器
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public static async Task<bool> ConnectServer(string uri)
{
webSocket = new ClientWebSocket(); //用于连接到Aria2Rpc的客户端
cancellationToken = new CancellationToken(); //传播有关应取消操作的通知
bool status = false; //储存连接状态
try
{
//连接服务器
await Aria2.webSocket.ConnectAsync(new Uri(uri), Aria2.cancellationToken);
}
catch
{
status = false;
}
//检查连接是否成功
if (Aria2.webSocket.State == WebSocketState.Open)
{
status = true;
}
return status;
}
/// <summary>
/// JsonClass类转为json格式
/// </summary>
/// <param name="json"></param>
/// <returns></returns>
private static string ToJson(JsonClass json)
{
string str = "";
str = "{" + "\"jsonrpc\":\"" + json._jsonrpc + "\",\"id\":\"" + json._id + "\",\"method\":\"" + json._method + "\",\"params\":[";
for (int i = 0; i < json._params.Count; i++)
{
if(json._method == "aria2.addUri")
{
str += "[\"" + json._params[i] + "\"]";
}
else if(json._method == "aria2.tellStatus")
{
if(i == 0)
{
str += "\""