DeliveryServer_Connection.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using System;
  2. using Fleck;
  3. using Sers.Core.CL.MessageDelivery;
  4. using Vit.Core.Module.Log;
  5. using Vit.Core.Util.Pipelines;
  6. using Vit.Extensions.Json_Extensions;
  7. namespace Sers.CL.WebSocket
  8. {
  9. public class DeliveryServer_Connection : IDeliveryConnection
  10. {
  11. public Sers.Core.Util.StreamSecurity.SecurityManager securityManager { set => _securityManager = value; }
  12. Sers.Core.Util.StreamSecurity.SecurityManager _securityManager;
  13. /// <summary>
  14. /// 连接状态(0:waitForCertify; 2:certified; 4:waitForClose; 8:closed;)
  15. /// </summary>
  16. public byte state { get; set; } = DeliveryConnState.waitForCertify;
  17. /// <summary>
  18. /// 请勿处理耗时操作,需立即返回。接收到客户端的数据事件
  19. /// </summary>
  20. public Action<IDeliveryConnection, ArraySegment<byte>> OnGetFrame { internal get; set; }
  21. public Action<IDeliveryConnection> Conn_OnDisconnected { get; set; }
  22. public void SendFrameAsync(Vit.Core.Util.Pipelines.ByteData data)
  23. {
  24. if (data == null || socket == null) return;
  25. try
  26. {
  27. Int32 len = data.Count();
  28. data.Insert(0, len.Int32ToArraySegmentByte());
  29. var bytes = data.ToBytes();
  30. _securityManager?.Encryption(new ArraySegment<byte>(bytes, 4, bytes.Length - 4));
  31. socket.Send(bytes);
  32. }
  33. catch (Exception ex)
  34. {
  35. Logger.Error(ex);
  36. Close();
  37. }
  38. }
  39. public void Close()
  40. {
  41. if (socket == null) return;
  42. state = DeliveryConnState.closed;
  43. var socket_ = socket;
  44. socket = null;
  45. try
  46. {
  47. socket_.Close();
  48. }
  49. catch (Exception ex)
  50. {
  51. Logger.Error(ex);
  52. }
  53. try
  54. {
  55. Conn_OnDisconnected?.Invoke(this);
  56. }
  57. catch (Exception ex)
  58. {
  59. Logger.Error(ex);
  60. }
  61. }
  62. public void Init(IWebSocketConnection socket)
  63. {
  64. this.socket = socket;
  65. }
  66. /// <summary>
  67. /// 通信SOCKET
  68. /// </summary>
  69. public IWebSocketConnection socket { get; private set; }
  70. PipeFrame pipe = new PipeFrame();
  71. public void AppendData(ArraySegment<byte> data)
  72. {
  73. pipe.Write(data);
  74. while (pipe.TryRead_SersFile(out var msgFrame))
  75. {
  76. _securityManager?.Decryption(msgFrame);
  77. OnGetFrame.Invoke(this, msgFrame);
  78. }
  79. }
  80. }
  81. }