|
@@ -1,55 +1,39 @@
|
|
|
-using Microsoft.AspNetCore.Builder;
|
|
|
-using Microsoft.AspNetCore.Http;
|
|
|
-using Microsoft.Extensions.DependencyInjection;
|
|
|
-using Microsoft.Extensions.Primitives;
|
|
|
+using Microsoft.AspNetCore.Http;
|
|
|
using System.Net;
|
|
|
using System.Net.WebSockets;
|
|
|
-using System.Text;
|
|
|
-using static System.Runtime.InteropServices.JavaScript.JSType;
|
|
|
|
|
|
namespace EVCB_OCPP.WSServer.Service.WsService;
|
|
|
|
|
|
-public static class AppExtention
|
|
|
+public class WebsocketService<T> where T : WsSession
|
|
|
{
|
|
|
- public static void MapWsService(this WebApplication webApplication)
|
|
|
- {
|
|
|
- var protocals = new List<string>() { "", "ocpp1.6", "ocpp2.0" };
|
|
|
+ public WebsocketService() { }
|
|
|
|
|
|
- webApplication.UseWebSockets(new WebSocketOptions()
|
|
|
- {
|
|
|
- KeepAliveInterval = TimeSpan.FromSeconds(10)
|
|
|
- });
|
|
|
+ public Func<T, Task<bool>> ValidateHandshake;
|
|
|
+
|
|
|
+ public event EventHandler<T> NewSessionConnected;
|
|
|
|
|
|
- webApplication.Use(async (context, next) =>
|
|
|
+ public async Task AcceptWebSocket(HttpContext context)
|
|
|
+ {
|
|
|
+ if (!context.WebSockets.IsWebSocketRequest)
|
|
|
{
|
|
|
+ return;
|
|
|
+ }
|
|
|
|
|
|
- if (!context.WebSockets.IsWebSocketRequest)
|
|
|
- {
|
|
|
- await next(context);
|
|
|
- return;
|
|
|
- }
|
|
|
-
|
|
|
- var matched = context.WebSockets.WebSocketRequestedProtocols.Intersect(protocals);
|
|
|
- if (matched is null || !matched.Any())
|
|
|
- {
|
|
|
- await context.Response.WriteAsync("Protocol not matched");
|
|
|
- return;
|
|
|
- }
|
|
|
- using WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(matched.Last());
|
|
|
- var servcie = context.RequestServices.GetService<WebsocketService<WsClientData>>();
|
|
|
- await servcie.AddWebSocket(webSocket, context);
|
|
|
+ var portocol = await AcceptWebSocketHandler(context);
|
|
|
+ if (string.IsNullOrEmpty(portocol))
|
|
|
+ {
|
|
|
return;
|
|
|
- });
|
|
|
- }
|
|
|
-}
|
|
|
+ }
|
|
|
|
|
|
-public class WebsocketService<T> where T : WsSession
|
|
|
-{
|
|
|
- public WebsocketService() { }
|
|
|
+ using WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(portocol);
|
|
|
+ await AddWebSocket(webSocket, context);
|
|
|
+ }
|
|
|
|
|
|
- public Func<T, Task<bool>> ValidateHandshake;
|
|
|
+ internal virtual ValueTask<string> AcceptWebSocketHandler(HttpContext context)
|
|
|
+ {
|
|
|
+ return ValueTask.FromResult(string.Empty);
|
|
|
+ }
|
|
|
|
|
|
- public event EventHandler<T> NewSessionConnected;
|
|
|
|
|
|
public async Task AddWebSocket(WebSocket webSocket, HttpContext context)
|
|
|
{
|
|
@@ -109,10 +93,4 @@ public class WebsocketService<T> where T : WsSession
|
|
|
|
|
|
return toReturn;
|
|
|
}
|
|
|
-}
|
|
|
-
|
|
|
-public enum CloseReason
|
|
|
-{
|
|
|
- ClientClosing,
|
|
|
- ServerShutdown
|
|
|
}
|