TcpEventData{TData}.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using EventBus;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. namespace TcpEventBus
  8. {
  9. public class TcpEventData<TData> : IEventData<TData>,ISubscripData
  10. {
  11. public bool IsResultEvent => false;
  12. public bool IsAnonymous => false;
  13. public void Subscrip(byte[] data, Properties properties)
  14. {
  15. lock(_list)
  16. {
  17. TData t = MsgTool.GetValue<TData>(data);
  18. var temp = _list.Where(x => x.Value.Properties.FilterRule(properties) && x.Value.HasDelegate).Select(x=>x.Value).ToList();
  19. if (temp.Count == 0) return;
  20. temp.ForEach(x => x.Action.Invoke(this, new EventArgs<TData>(t, x.IntPtr, this)));
  21. }
  22. }
  23. public void SubscripData(byte[] data, Properties properties)
  24. {
  25. throw new NotSupportedException();
  26. }
  27. ConcurrentDictionary<Guid, ActionValue<TData>> _list = new ConcurrentDictionary<Guid, ActionValue<TData>>();
  28. private ISocket _Socket;
  29. internal TcpEventData(ISocket socket, string eventName, string hash)
  30. {
  31. _Socket = socket;
  32. EventName = eventName;
  33. Hash = hash;
  34. }
  35. public string EventName { get; }
  36. public string Hash { get; }
  37. public void Clear()
  38. {
  39. lock (_list)
  40. {
  41. _list.Clear();
  42. }
  43. }
  44. public void Publish(object sender, TData data, Properties? properties = null)
  45. {
  46. if (data == null || _Socket ==null) return;
  47. _Socket.Send(this.GetMsg(data,properties).GetBytes());
  48. }
  49. public Task PublishAsync(object sender, TData data, Properties? properties = null)
  50. {
  51. if (data == null || _Socket == null) return Task.CompletedTask;
  52. return Task.Run(()=> _Socket.Send(this.GetMsg(data, properties).GetBytes()));
  53. }
  54. public Guid Subscrip(Action<object, EventArgs<TData>> action, Properties? properties = null)
  55. {
  56. lock (_list)
  57. {
  58. ArgumentNullException.ThrowIfNull(action);
  59. properties ??= Properties.Default;
  60. var temp = new ActionValue<TData>(action, properties);
  61. _list[temp.IntPtr] = temp;
  62. return temp.IntPtr;
  63. }
  64. }
  65. public void UnSubscrip(Guid guid)
  66. {
  67. lock (_list)
  68. {
  69. if (guid == Guid.Empty) return;
  70. _list.TryRemove(guid, out _);
  71. }
  72. }
  73. }
  74. }