Adds onOpenHandler

This commit is contained in:
Dmitri Shimanski
2025-03-29 04:22:57 +03:00
parent 2af82e6fc5
commit 4a22cf3337
3 changed files with 22 additions and 3 deletions

View File

@@ -0,0 +1,10 @@
using Microsoft.AspNetCore.Http;
using yawaflua.WebSockets.Models.Interfaces;
namespace yawaflua.WebSockets.Core;
public class WebSocketConfig
{
public Func<IWebSocket, HttpContext, Task>? OnOpenHandler { get; set; } = null;
}

View File

@@ -17,11 +17,12 @@ public class WebSocketRouter
internal static readonly List<IWebSocketClient> Clients = new();
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<WebSocketRouter> _logger;
public WebSocketRouter(IServiceProvider serviceProvider, ILogger<WebSocketRouter> logger)
private readonly WebSocketConfig WebSocketConfig;
public WebSocketRouter(IServiceProvider serviceProvider, ILogger<WebSocketRouter> logger, WebSocketConfig webSocketConfig)
{
_serviceProvider = serviceProvider;
this._logger = logger;
WebSocketConfig = webSocketConfig;
DiscoverHandlers();
Task.Run(() =>
{
@@ -146,6 +147,13 @@ public class WebSocketRouter
{
var client = new WebSocketClient(context, webSocket, path);
Clients.Add(client);
await Task.Run(async () =>
{
if (WebSocketConfig.OnOpenHandler != null)
await WebSocketConfig.OnOpenHandler((webSocket as IWebSocket)!, context);
}, cts);
var buffer = new byte[1024 * 4];
while (webSocket.State == WebSocketState.Open)
{

View File

@@ -8,11 +8,12 @@ namespace yawaflua.WebSockets;
public static class ServiceBindings
{
public static IServiceCollection SettingUpWebSockets(this IServiceCollection isc)
public static IServiceCollection SettingUpWebSockets(this IServiceCollection isc, Action<WebSocketOptions>? socketOptions = null)
{
isc.AddSingleton<WebSocketRouter>();
isc.AddScoped<IWebSocketManager, WebSocketManager>();
isc.AddSingleton<WebSocketMiddleware>();
isc.Configure("WebSocketOptions", socketOptions);
return isc;
}