PartyDamage/Client.cs

59 lines
1.9 KiB
C#
Raw Normal View History

2024-07-24 20:30:12 +00:00
using System.Net.WebSockets;
using System.Text;
namespace PartyDamage;
public class Client : IDisposable {
private ClientWebSocket WebSocket { get; }
private CancellationTokenSource TokenSource { get; }
private Task? MainTask { get; set; }
private bool _disposed;
internal Client() {
this.WebSocket = new ClientWebSocket();
this.TokenSource = new CancellationTokenSource();
this.MainTask = Task.Run(async () => {
while (!this._disposed) {
try {
await this.Main();
} catch (Exception ex) {
Plugin.Log.Error(ex, "Error in WebSocket loop");
await Task.Delay(TimeSpan.FromSeconds(3));
}
}
});
}
public void Dispose() {
if (this._disposed) {
return;
}
this._disposed = true;
this.TokenSource.Cancel();
this.WebSocket.Dispose();
this.MainTask?.Dispose();
}
private async Task Main() {
await this.WebSocket.ConnectAsync(new Uri("http://127.0.0.1:10501/"), this.TokenSource.Token);
var msg = "{\"call\": \"subscribe\", \"events\": [\"CombatData\"]}";
var msgBytes = Encoding.UTF8.GetBytes(msg);
await this.WebSocket.SendAsync(msgBytes, WebSocketMessageType.Text, true, this.TokenSource.Token);
var received = new List<byte>();
while (this.WebSocket.State == WebSocketState.Open) {
var bytes = new byte[1024];
var resp = await this.WebSocket.ReceiveAsync(bytes, this.TokenSource.Token);
received.AddRange(bytes[..resp.Count]);
if (resp.EndOfMessage) {
var text = Encoding.UTF8.GetString(bytes.AsSpan());
received.Clear();
Plugin.Log.Info(text);
}
}
Plugin.Log.Info("websocket loop shut down");
}
}