iFactory.Godot/BITKit/Scripts/Web/HttpGet.cs

88 lines
2.3 KiB
C#
Raw Normal View History

2023-06-29 01:01:52 +08:00
using Godot;
using System;
using System.Threading;
using BITKit.Packages.Core.LazyLoad;
2023-11-02 20:58:36 +08:00
using HttpClient = System.Net.Http.HttpClient;
2023-06-29 01:01:52 +08:00
namespace BITKit;
public partial class HttpGet : Node,IActivable
{
/// <summary>
/// 访问的Url
/// </summary>
[Export] private string url;
/// <summary>
/// 是否启用
/// </summary>
[Export]
public bool Enabled { get; set; } = true;
[Signal]
public delegate void OnGetEventHandler(string httpContext);
2023-11-30 00:27:34 +08:00
[Signal]
public delegate void OnExceptionEventHandler(string exception);
2023-06-29 01:01:52 +08:00
/// <summary>
/// 请求数据的间隔
/// </summary>
private readonly IntervalTimer _intervalTimer = new(1);
/// <summary>
/// http客户端
/// </summary>
2023-11-02 20:58:36 +08:00
private readonly HttpClient httpClient=new();
2023-06-29 01:01:52 +08:00
/// <summary>
/// 取消令牌用于取消Http Get
/// </summary>
private CancellationToken _cancellationToken;
2023-11-02 20:58:36 +08:00
private bool allowNextRequest = true;
2023-06-29 01:01:52 +08:00
public override void _Ready()
{
_cancellationToken = new CancellationToken();
}
2023-11-02 20:58:36 +08:00
2023-06-29 01:01:52 +08:00
/// <summary>
/// 物理帧用于控制并发和间隔的同时请求数据
/// </summary>
/// <param name="delta"></param>
public override void _PhysicsProcess(double delta)
{
2023-11-02 20:58:36 +08:00
if (Enabled is false) return;
2023-06-29 01:01:52 +08:00
//等待依赖加载
//请求间隔控制+请求并发控制
2023-11-02 20:58:36 +08:00
if (_intervalTimer.Allow is false) return;
2023-06-29 01:01:52 +08:00
//如果url为空
if (string.IsNullOrEmpty(url)) return;
//发送请求
2023-11-02 20:58:36 +08:00
if (allowNextRequest)
Request();
2023-06-29 01:01:52 +08:00
}
private async void Request()
{
2023-11-02 20:58:36 +08:00
allowNextRequest = false;
2023-06-29 01:01:52 +08:00
//获取json
try
{
2023-11-02 20:58:36 +08:00
var json = await httpClient.GetStringAsync(url, _cancellationToken);
2023-06-29 01:01:52 +08:00
//取消执行,如果已取消令牌
_cancellationToken.ThrowIfCancellationRequested();
//调用回调
EmitSignal(nameof(OnGet), json);
}
catch (InvalidOperationException)
{
2023-08-18 11:03:06 +08:00
BIT4Log.Warning(url);
2023-06-29 01:01:52 +08:00
}
catch (OperationCanceledException)
{
}
2023-11-30 00:27:34 +08:00
catch (Exception e)
{
EmitSignal(nameof(OnException), e.Message);
}
2023-11-02 20:58:36 +08:00
allowNextRequest = true;
2023-06-29 01:01:52 +08:00
}
public void SetActive(bool active) => Enabled=active;
}