WsSession.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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 SessionID { get; set; }
  16. public IPEndPoint Endpoint { get; internal set; }
  17. public DateTime LastActiveTime { get; set; }
  18. private WebSocket _WebSocket;
  19. public WebSocket ClientWebSocket
  20. {
  21. get => _WebSocket;
  22. set
  23. {
  24. Init(value);
  25. }
  26. }
  27. public WebSocketState State => ClientWebSocket.State;
  28. public string SecWebSocketProtocol => ClientWebSocket.SubProtocol;
  29. public SemaphoreSlim EndConnSemaphore { get; } = new SemaphoreSlim(0);
  30. //public event OCPPClientDataEventHandler<WsSession, String> m_ReceiveData;
  31. public event EventHandler<string> SessionClosed;
  32. private CancellationTokenSource disconnectCancellationTokenSource = new CancellationTokenSource();
  33. private Task ReceiveLoopTask;
  34. private readonly ILogger<WsSession> logger;
  35. private void Init(WebSocket webSocket)
  36. {
  37. _WebSocket = webSocket;
  38. LastActiveTime = DateTime.UtcNow;
  39. ReceiveLoopTask = StartReceivd(webSocket, disconnectCancellationTokenSource.Token);
  40. }
  41. private async Task StartReceivd(WebSocket webSocket, CancellationToken token)
  42. {
  43. logger.LogInformation("{id} {func} {Path} Start", SessionID, nameof(StartReceivd), Path);
  44. byte[] prevBuffer = new byte[0];
  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. prevBuffer = receivdBuffer;
  69. receivdBuffer = new byte[1024 * 4 * bufferExpand];
  70. Array.Copy(prevBuffer, 0, receivdBuffer, 0, receivedBytes);
  71. Array.Copy(tempReceiveBuffer, 0, receivdBuffer, receivedBytes, result.Count);
  72. receivedBytes += result.Count;
  73. if (!result.EndOfMessage)
  74. {
  75. bufferExpand++;
  76. continue;
  77. }
  78. var received = Encoding.UTF8.GetString(receivdBuffer, 0, receivedBytes);
  79. //logger.LogInformation("{func}:{Path} {value}", nameof(StartReceivd), Path, received);
  80. HandleReceivedData(received);
  81. bufferExpand = 1;
  82. receivedBytes = 0;
  83. }
  84. }
  85. internal virtual void HandleReceivedData(string data)
  86. {
  87. }
  88. internal Task Send(string dataString)
  89. {
  90. //logger.LogInformation("{func}:{Path} {value}", nameof(Send), Path, dataString);
  91. var data = Encoding.UTF8.GetBytes(dataString);
  92. return Send(data);
  93. }
  94. internal Task Close()
  95. {
  96. return ServerClose();
  97. }
  98. private async Task Send(byte[] data)
  99. {
  100. try
  101. {
  102. await ClientWebSocket.SendAsync(data, WebSocketMessageType.Text, endOfMessage: true, cancellationToken: disconnectCancellationTokenSource.Token);
  103. }
  104. catch (Exception e)
  105. {
  106. logger.LogInformation("{func} {Path} exception:{msg}", nameof(Send), Path, e.Message);
  107. }
  108. }
  109. private Task ServerClose()
  110. {
  111. logger.LogInformation("{func}:{Path}", nameof(ServerClose), Path);
  112. SessionClosed?.Invoke(this, "ServerShutdown");
  113. return InternalClose(WebSocketCloseStatus.NormalClosure, "ServerShutdown");
  114. }
  115. private Task GracefulClose(WebSocketCloseStatus closeStatus)
  116. {
  117. logger.LogInformation("{func}:{Path} {value}", nameof(GracefulClose), Path, closeStatus);
  118. SessionClosed?.Invoke(this, closeStatus.ToString());
  119. return InternalClose(closeStatus, null);
  120. }
  121. private Task BruteClose(string description)
  122. {
  123. logger.LogInformation("{func}:{Path} {value}", nameof(ServerClose), Path, description);
  124. SessionClosed?.Invoke(this, description);
  125. return InternalClose(WebSocketCloseStatus.EndpointUnavailable, description);
  126. }
  127. private async Task InternalClose(WebSocketCloseStatus closeStatus, string description)
  128. {
  129. try
  130. {
  131. await _WebSocket.CloseAsync(closeStatus, description, default);
  132. }
  133. catch
  134. {
  135. }
  136. finally
  137. {
  138. _WebSocket.Dispose();
  139. }
  140. disconnectCancellationTokenSource.Cancel();
  141. EndConnSemaphore.Release();
  142. }
  143. }