2508271256

HeartbeatSender添加Try-Catch與Writelog
This commit is contained in:
jasonchenwork 2025-08-27 12:57:34 +08:00
parent 5ddd093273
commit 2466c8cb6a

View File

@ -18,10 +18,10 @@ public class heartbeatSender
private string branchName = ""; private string branchName = "";
private string heartbeatDomain = ""; private string heartbeatDomain = "";
private CancellationTokenSource? cancellationTokenSource; private CancellationTokenSource? cancellationTokenSource;
public static Dictionary<string, string> DbData= new Dictionary<string, string>() ; public static Dictionary<string, string> DbData = new Dictionary<string, string>();
public heartbeatSender() public heartbeatSender()
{ {
this.heartbeatDomain = Utils.Env.Get("HeartBeatUrl", ""); this.heartbeatDomain = Utils.Env.Get("HeartBeatUrl", "");
bool loginSuccess = LoginAndGetTokenAsync().GetAwaiter().GetResult(); bool loginSuccess = LoginAndGetTokenAsync().GetAwaiter().GetResult();
Console.WriteLine(loginSuccess ? "心跳登入成功" : "心跳登入失敗"); Console.WriteLine(loginSuccess ? "心跳登入成功" : "心跳登入失敗");
// 在建構子中啟動背景心跳任務 // 在建構子中啟動背景心跳任務
@ -51,6 +51,7 @@ public class heartbeatSender
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"心跳任務錯誤:{ex.Message}"); Console.WriteLine($"心跳任務錯誤:{ex.Message}");
WriteLog(ex.Message);
await Task.Delay(5000); // 錯誤後延遲再跑 await Task.Delay(5000); // 錯誤後延遲再跑
} }
} }
@ -58,109 +59,212 @@ public class heartbeatSender
public void Stop() public void Stop()
{ {
cancellationTokenSource?.Cancel(); try
Console.WriteLine("心跳任務已停止"); {
cancellationTokenSource?.Cancel();
Console.WriteLine("心跳任務已停止");
}
catch (Exception ex)
{
Console.WriteLine($"心跳任務錯誤:{ex.Message}");
WriteLog(ex.Message);
}
} }
public async Task<bool> LoginAndGetTokenAsync() public async Task<bool> LoginAndGetTokenAsync()
{ {
var url = $"{heartbeatDomain.TrimEnd('/')}/api/room/receiveRegister"; try
var loginPayload = new
{ {
email = "MachineKTV@gmail.com", var url = $"{heartbeatDomain.TrimEnd('/')}/api/room/receiveRegister";
password = "aa147258-" var loginPayload = new
};
var result = await SendPostAsync<JsonElement>(url, loginPayload);
if (result.ValueKind == JsonValueKind.Object &&
result.TryGetProperty("data", out JsonElement data))
{
token = data.GetProperty("token").GetString()!;
branchName = data.GetProperty("branch_name").GetString()!;
var Dbdatas = data.GetProperty("other_set");
if (Dbdatas.ValueKind == JsonValueKind.Object)
{ {
foreach (JsonProperty property in Dbdatas.EnumerateObject()) email = "MachineKTV@gmail.com",
password = "aa147258-"
};
var result = await SendPostAsync<JsonElement>(url, loginPayload);
if (result.ValueKind == JsonValueKind.Object &&
result.TryGetProperty("data", out JsonElement data))
{
token = data.GetProperty("token").GetString()!;
branchName = data.GetProperty("branch_name").GetString()!;
var Dbdatas = data.GetProperty("other_set");
if (Dbdatas.ValueKind == JsonValueKind.Object)
{ {
DbData.Add(property.Name.ToString(), property.Value.ToString()); foreach (JsonProperty property in Dbdatas.EnumerateObject())
{
DbData.Add(property.Name.ToString(), property.Value.ToString());
}
} }
return true;
} }
return true;
return false;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return default;
} }
return false;
} }
public async Task SendHeartbeatAsync() public async Task SendHeartbeatAsync()
{ {
var url = $"{heartbeatDomain.TrimEnd('/')}/api/room/heartbeat"; try
string hostName = Dns.GetHostName();
var heartbeatPayload = new
{ {
branch_name = branchName, var url = $"{heartbeatDomain.TrimEnd('/')}/api/room/heartbeat";
hostname = "PC" + hostName[^3..], string hostName = Dns.GetHostName();
ip = GetLocalIPv4(),
cpu = GetCpuUsage(), var heartbeatPayload = new
memory = GetTotalMemoryInMB(), {
disk = GetDiskTotalSizeInGB() branch_name = branchName,
}; hostname = "PC" + hostName[^3..],
ip = GetLocalIPv4(),
cpu = GetCpuUsage(),
memory = GetTotalMemoryInMB(),
disk = GetDiskTotalSizeInGB()
};
await SendPostAsync<JsonElement>(url, heartbeatPayload, token);
Console.WriteLine($"心跳送出成功: {DateTime.Now:HH:mm:ss}");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return;
}
await SendPostAsync<JsonElement>(url, heartbeatPayload, token);
Console.WriteLine($"心跳送出成功: {DateTime.Now:HH:mm:ss}");
} }
private async Task<T?> SendPostAsync<T>(string url, object payload, string? bearerToken = null) private async Task<T?> SendPostAsync<T>(string url, object payload, string? bearerToken = null)
{ {
var json = JsonSerializer.Serialize(payload); try
var content = new StringContent(json, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, url)
{ {
Content = content var json = JsonSerializer.Serialize(payload);
}; var content = new StringContent(json, Encoding.UTF8, "application/json");
if (!string.IsNullOrWhiteSpace(bearerToken)) var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = content
};
if (!string.IsNullOrWhiteSpace(bearerToken))
{
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearerToken);
}
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseJson = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(responseJson);
}
catch (Exception ex)
{ {
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", bearerToken); Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return default(T);
} }
var response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
string responseJson = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<T>(responseJson);
} }
private static string GetLocalIPv4() private static string GetLocalIPv4()
{ {
foreach (var ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList) try
{ {
if (ip.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(ip)) foreach (var ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
return ip.ToString(); {
if (ip.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(ip))
return ip.ToString();
}
return "127.0.0.1";
} }
return "127.0.0.1"; catch (Exception ex)
{
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return "";
}
} }
private float GetCpuUsage() private float GetCpuUsage()
{ {
using var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); try
cpuCounter.NextValue(); {
Thread.Sleep(100); using var cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
return cpuCounter.NextValue(); cpuCounter.NextValue();
Thread.Sleep(100);
return cpuCounter.NextValue();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return float.NaN;
}
} }
private float GetTotalMemoryInMB() private float GetTotalMemoryInMB()
{ {
var ci = new ComputerInfo(); try
return (ci.TotalPhysicalMemory - ci.AvailablePhysicalMemory) / 1024f; {
var ci = new ComputerInfo();
return (ci.TotalPhysicalMemory - ci.AvailablePhysicalMemory) / 1024f;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return float.NaN;
}
} }
private float GetDiskTotalSizeInGB(string driveLetter = "C") private float GetDiskTotalSizeInGB(string driveLetter = "C")
{ {
var drive = new DriveInfo(driveLetter); try
return drive.TotalSize / (1024f * 1024f * 1024f); {
var drive = new DriveInfo(driveLetter);
return drive.TotalSize / (1024f * 1024f * 1024f);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
WriteLog(ex.Message);
return float.NaN;
}
}
public static void WriteLog(string message)
{
// 指定日志文件的路径
string logFilePath = Path.Combine(Application.StartupPath, "txt", "mainlog.txt");
try
{
// 使用 StreamWriter 来向日志文件追加文本
using (StreamWriter writer = new StreamWriter(logFilePath, true))
{
writer.WriteLine(String.Format("[{0}] {1}", DateTime.Now, message));
}
}
catch (Exception ex)
{
// 如果写入日志文件时发生错误,这里可以处理这些异常
// 例如:打印到控制台
Console.WriteLine(String.Format("Error writing to log file: {0}", ex.Message));
}
} }
} }