WsSession.cs 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.Extensions.Logging;
  3. using System.Net;
  4. using System.Net.WebSockets;
  5. using System.Text;
  6. namespace EVCB_OCPP.WSServer.Service.WsService;
  7. public class WsSession
  8. {
  9. public WsSession(ILogger<WsSession> logger)
  10. {
  11. this.logger = logger;
  12. }
  13. public PathString? Path { get; set; }
  14. public string UriScheme { get; set; }
  15. public string AuthHeader { get; set; }
  16. public string SessionID { get; set; }
  17. public IPEndPoint Endpoint { get; internal set; }
  18. //public StringValues Origin { get; internal set; }
  19. public DateTime LastActiveTime { get; set; }
  20. private WebSocket _WebSocket;
  21. public WebSocket ClientWebSocket
  22. {
  23. get => _WebSocket;
  24. set
  25. {
  26. Init(value);
  27. }
  28. }
  29. public WebSocketState State => ClientWebSocket.State;
  30. public string SecWebSocketProtocol => ClientWebSocket.SubProtocol;
  31. public SemaphoreSlim EndConnSemaphore { get; } = new SemaphoreSlim(0);
  32. //public event OCPPClientDataEventHandler<WsSession, String> m_ReceiveData;
  33. public event EventHandler<string> SessionClosed;
  34. private CancellationTokenSource disconnectCancellationTokenSource = new CancellationTokenSource();
  35. private Task ReceiveLoopTask;
  36. private readonly ILogger<WsSession> logger;
  37. private void Init(WebSocket webSocket)
  38. {
  39. _WebSocket = webSocket;
  40. ReceiveLoopTask = StartReceivd(webSocket, disconnectCancellationTokenSource.Token);
  41. }
  42. private async Task StartReceivd(WebSocket webSocket, CancellationToken token)
  43. {
  44. logger.LogInformation("{func}:{Path} Start", nameof(StartReceivd), Path);
  45. byte[] receivdBuffer = new byte[0];
  46. int bufferExpand = 1;
  47. int receivedBytes = 0;
  48. while (!token.IsCancellationRequested)
  49. {
  50. var tempReceiveBuffer = new byte[1024 * 4];
  51. WebSocketReceiveResult result = null;
  52. try
  53. {
  54. result = await webSocket.ReceiveAsync(new ArraySegment<byte>(tempReceiveBuffer), token);
  55. }
  56. catch (Exception e)
  57. {
  58. _ = BruteClose(e.Message);
  59. break;
  60. }
  61. LastActiveTime = DateTime.UtcNow;
  62. if (result == null || result.CloseStatus.HasValue)
  63. {
  64. //closed gracefully
  65. await GracefulClose(result.CloseStatus.Value);
  66. break;
  67. }
  68. receivdBuffer = new byte[1024 * 4 * bufferExpand];
  69. Array.Copy(tempReceiveBuffer, 0, receivdBuffer, receivedBytes, result.Count);
  70. receivedBytes += result.Count;
  71. if (!result.EndOfMessage)
  72. {
  73. bufferExpand++;
  74. continue;
  75. }
  76. var received = Encoding.UTF8.GetString(receivdBuffer, 0, receivedBytes);
  77. logger.LogInformation("{func}:{Path} {value}", nameof(StartReceivd), Path, received);
  78. HandleReceivedData(received);
  79. bufferExpand = 1;
  80. receivedBytes = 0;
  81. }
  82. }
  83. internal virtual void HandleReceivedData(string data)
  84. {
  85. }
  86. internal Task Send(string dataString)
  87. {
  88. logger.LogInformation("{func}:{Path} {value}", nameof(Send), Path, dataString);
  89. var data = Encoding.UTF8.GetBytes(dataString);
  90. return Send(data);
  91. }
  92. internal Task Close()
  93. {
  94. return ServerClose();
  95. }
  96. private async Task Send(byte[] data)
  97. {
  98. try
  99. {
  100. await ClientWebSocket.SendAsync(data, WebSocketMessageType.Text, endOfMessage: true, cancellationToken: disconnectCancellationTokenSource.Token);
  101. }
  102. catch (Exception e)
  103. {
  104. logger.LogInformation("{func}:{Path} exception:{msg}", nameof(Send), Path, e.Message);
  105. }
  106. }
  107. private Task ServerClose()
  108. {
  109. logger.LogInformation("{func}:{Path}", nameof(ServerClose), Path);
  110. SessionClosed?.Invoke(this, "ServerShutdown");
  111. return InternalClose(WebSocketCloseStatus.NormalClosure, "ServerShutdown");
  112. }
  113. private Task GracefulClose(WebSocketCloseStatus closeStatus)
  114. {
  115. logger.LogInformation("{func}:{Path} {value}", nameof(GracefulClose), Path, closeStatus);
  116. SessionClosed?.Invoke(this, closeStatus.ToString());
  117. return InternalClose(closeStatus , null);
  118. }
  119. private Task BruteClose(string description)
  120. {
  121. logger.LogInformation("{func}:{Path} {value}", nameof(ServerClose), Path, description);
  122. SessionClosed?.Invoke(this, description);
  123. return InternalClose(WebSocketCloseStatus.EndpointUnavailable, description);
  124. }
  125. private async Task InternalClose(WebSocketCloseStatus closeStatus, string description)
  126. {
  127. try
  128. {
  129. await _WebSocket.CloseAsync(closeStatus, description, default);
  130. }
  131. catch
  132. {
  133. }
  134. finally
  135. {
  136. _WebSocket.Dispose();
  137. }
  138. disconnectCancellationTokenSource.Cancel();
  139. EndConnSemaphore.Release();
  140. }
  141. }