TcpAnonymousEventData.cs 2.7 KB

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