56 lines
1.8 KiB
C#
56 lines
1.8 KiB
C#
using System.Text.Json;
|
|
using CommonSocketLibrary.Abstract;
|
|
using Serilog;
|
|
|
|
namespace CommonSocketLibrary.Common
|
|
{
|
|
public class WebSocketClient : SocketClient<WebSocketMessage>
|
|
{
|
|
private readonly HandlerManager<WebSocketClient, IWebSocketHandler> _handlerManager;
|
|
private readonly HandlerTypeManager<WebSocketClient, IWebSocketHandler> _handlerTypeManager;
|
|
|
|
public WebSocketClient(
|
|
ILogger logger,
|
|
HandlerManager<WebSocketClient, IWebSocketHandler> handlerManager,
|
|
HandlerTypeManager<WebSocketClient, IWebSocketHandler> typeManager,
|
|
JsonSerializerOptions serializerOptions
|
|
) : base(logger, serializerOptions)
|
|
{
|
|
_handlerManager = handlerManager;
|
|
_handlerTypeManager = typeManager;
|
|
}
|
|
|
|
protected override WebSocketMessage GenerateMessage<T>(int opcode, T data)
|
|
{
|
|
return new WebSocketMessage()
|
|
{
|
|
OpCode = opcode,
|
|
Data = data
|
|
};
|
|
}
|
|
|
|
protected override async Task OnResponseReceived(WebSocketMessage? data)
|
|
{
|
|
if (data == null)
|
|
return;
|
|
|
|
string content = data.Data?.ToString() ?? string.Empty;
|
|
_logger.Verbose("RX #" + data.OpCode + ": " + content);
|
|
|
|
if (!_handlerTypeManager.HandlerTypes.TryGetValue(data.OpCode, out Type? type) || type == null)
|
|
return;
|
|
|
|
var obj = JsonSerializer.Deserialize(content, type, _options);
|
|
await _handlerManager.Execute(this, data.OpCode, obj);
|
|
}
|
|
|
|
protected override async Task OnMessageSend(int opcode, string? content)
|
|
{
|
|
_logger.Verbose("TX #" + opcode + ": " + content);
|
|
}
|
|
|
|
protected override async Task OnConnection()
|
|
{
|
|
}
|
|
}
|
|
} |