yep
This commit is contained in:
@@ -4,12 +4,15 @@ using Shogi.Contracts.Types;
|
||||
using System.Buffers;
|
||||
using System.Net.WebSockets;
|
||||
using System.Text.Json;
|
||||
using static Shogi.UI.Shared.Events;
|
||||
|
||||
namespace Shogi.UI.Shared;
|
||||
|
||||
public class ShogiSocket : IDisposable
|
||||
{
|
||||
public event EventHandler<SessionCreatedSocketMessage>? OnCreateGameMessage;
|
||||
public event AsyncEventHandler? OnSessionCreated;
|
||||
public event AsyncEventHandler? OnSessionJoined;
|
||||
public event AsyncEventHandler<PlayerHasMovedMessage>? OnPlayerMoved;
|
||||
|
||||
private readonly ClientWebSocket socket;
|
||||
private readonly JsonSerializerOptions serializerOptions;
|
||||
@@ -37,8 +40,11 @@ public class ShogiSocket : IDisposable
|
||||
await socket.ConnectAsync(this.uriBuilder.Uri, cancelToken.Token);
|
||||
Console.WriteLine("Socket Connected");
|
||||
// Fire and forget! I'm way too lazy to write my own javascript interop to a web worker. Nooo thanks.
|
||||
var listening = Listen().ContinueWith(antecedent =>
|
||||
_ = Listen().ContinueWith(async antecedent =>
|
||||
{
|
||||
Console.WriteLine($"Socket fault. {antecedent.Exception}");
|
||||
this.cancelToken.Cancel();
|
||||
await this.socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Page was probably closed or refresh.", CancellationToken.None);
|
||||
if (antecedent.Exception != null)
|
||||
{
|
||||
throw antecedent.Exception;
|
||||
@@ -58,16 +64,33 @@ public class ShogiSocket : IDisposable
|
||||
.GetProperty(nameof(ISocketResponse.Action))
|
||||
.Deserialize<SocketAction>();
|
||||
|
||||
Console.WriteLine($"Socket action: {action}");
|
||||
switch (action)
|
||||
{
|
||||
case SocketAction.SessionCreated:
|
||||
Console.WriteLine("Session created event.");
|
||||
this.OnCreateGameMessage?.Invoke(this, JsonSerializer.Deserialize<SessionCreatedSocketMessage>(memory, this.serializerOptions)!);
|
||||
if (this.OnSessionCreated is not null)
|
||||
{
|
||||
await this.OnSessionCreated();
|
||||
}
|
||||
break;
|
||||
case SocketAction.SessionJoined:
|
||||
if (this.OnSessionJoined is not null)
|
||||
{
|
||||
await this.OnSessionJoined();
|
||||
}
|
||||
break;
|
||||
case SocketAction.PieceMoved:
|
||||
if (this.OnPlayerMoved is not null)
|
||||
{
|
||||
var args = JsonSerializer.Deserialize<PlayerHasMovedMessage>(memory[..result.Count], serializerOptions);
|
||||
await this.OnPlayerMoved(args!);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
throw new NotImplementedException($"Socket message for action:{action} is not implemented.");
|
||||
}
|
||||
}
|
||||
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Socket closed because cancellation token was cancelled.", CancellationToken.None);
|
||||
if (!cancelToken.IsCancellationRequested)
|
||||
{
|
||||
throw new InvalidOperationException("Stopped socket listening without cancelling.");
|
||||
|
||||
Reference in New Issue
Block a user