WsSession.cs 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. ReceiveLoopTask = StartReceivd(webSocket, disconnectCancellationTokenSource.Token);
  39. }
  40. private async Task StartReceivd(WebSocket webSocket, CancellationToken token)
  41. {
  42. logger.LogInformation("{id} {func} {Path} Start", SessionID, nameof(StartReceivd), Path);
  43. byte[] receivdBuffer = new byte[0];
  44. int bufferExpand = 1;
  45. int receivedBytes = 0;
  46. while (!token.IsCancellationRequested)
  47. {
  48. var tempReceiveBuffer = new byte[1024 * 4];
  49. WebSocketReceiveResult result = null;
  50. try
  51. {
  52. result = await webSocket.ReceiveAsync(new ArraySegment<byte>(tempReceiveBuffer), token);
  53. }
  54. catch (Exception e)
  55. {
  56. _ = BruteClose(e.Message);
  57. break;
  58. }
  59. LastActiveTime = DateTime.UtcNow;
  60. if (result == null || result.CloseStatus.HasValue)
  61. {
  62. //closed gracefully
  63. await GracefulClose(result.CloseStatus.Value);
  64. break;
  65. }
  66. receivdBuffer = new byte[1024 * 4 * bufferExpand];
  67. Array.Copy(tempReceiveBuffer, 0, receivdBuffer, receivedBytes, result.Count);
  68. receivedBytes += result.Count;
  69. if (!result.EndOfMessage)
  70. {
  71. bufferExpand++;
  72. continue;
  73. }
  74. var received = Encoding.UTF8.GetString(receivdBuffer, 0, receivedBytes);
  75. //logger.LogInformation("{func}:{Path} {value}", nameof(StartReceivd), Path, received);
  76. HandleReceivedData(received);
  77. bufferExpand = 1;
  78. receivedBytes = 0;
  79. }
  80. }
  81. internal virtual void HandleReceivedData(string data)
  82. {
  83. }
  84. internal Task Send(string dataString)
  85. {
  86. //logger.LogInformation("{func}:{Path} {value}", nameof(Send), Path, dataString);
  87. var data = Encoding.UTF8.GetBytes(dataString);
  88. return Send(data);
  89. }
  90. internal Task Close()
  91. {
  92. return ServerClose();
  93. }
  94. private async Task Send(byte[] data)
  95. {
  96. try
  97. {
  98. await ClientWebSocket.SendAsync(data, WebSocketMessageType.Text, endOfMessage: true, cancellationToken: disconnectCancellationTokenSource.Token);
  99. }
  100. catch (Exception e)
  101. {
  102. logger.LogInformation("{func} {Path} exception:{msg}", nameof(Send), Path, e.Message);
  103. }
  104. }
  105. private Task ServerClose()
  106. {
  107. logger.LogInformation("{func}:{Path}", nameof(ServerClose), Path);
  108. SessionClosed?.Invoke(this, "ServerShutdown");
  109. return InternalClose(WebSocketCloseStatus.NormalClosure, "ServerShutdown");
  110. }
  111. private Task GracefulClose(WebSocketCloseStatus closeStatus)
  112. {
  113. logger.LogInformation("{func}:{Path} {value}", nameof(GracefulClose), Path, closeStatus);
  114. SessionClosed?.Invoke(this, closeStatus.ToString());
  115. return InternalClose(closeStatus , null);
  116. }
  117. private Task BruteClose(string description)
  118. {
  119. logger.LogInformation("{func}:{Path} {value}", nameof(ServerClose), Path, description);
  120. SessionClosed?.Invoke(this, description);
  121. return InternalClose(WebSocketCloseStatus.EndpointUnavailable, description);
  122. }
  123. private async Task InternalClose(WebSocketCloseStatus closeStatus, string description)
  124. {
  125. try
  126. {
  127. await _WebSocket.CloseAsync(closeStatus, description, default);
  128. }
  129. catch
  130. {
  131. }
  132. finally
  133. {
  134. _WebSocket.Dispose();
  135. }
  136. disconnectCancellationTokenSource.Cancel();
  137. EndConnSemaphore.Release();
  138. }
  139. }