123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- using EventBus;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace TcpEventBus
- {
- public class TcpEventData<TData> : IEventData<TData>,ISubscripData
- {
- public bool IsResultEvent => false;
- public bool IsAnonymous => false;
- public void Subscrip(byte[] data, Properties properties)
- {
- lock(_list)
- {
- TData t = MsgTool.GetValue<TData>(data);
- var temp = _list.Where(x => x.Value.Properties.FilterRule(properties) && x.Value.HasDelegate).Select(x=>x.Value).ToList();
- if (temp.Count == 0) return;
- temp.ForEach(x => x.Action.Invoke(this, new EventArgs<TData>(t, x.IntPtr, this)));
- }
- }
- public void SubscripData(byte[] data, Properties properties)
- {
- throw new NotSupportedException();
- }
- ConcurrentDictionary<Guid, ActionValue<TData>> _list = new ConcurrentDictionary<Guid, ActionValue<TData>>();
- private ISocket _Socket;
- internal TcpEventData(ISocket socket, string eventName, string hash)
- {
- _Socket = socket;
- EventName = eventName;
- Hash = hash;
- }
- public string EventName { get; }
- public string Hash { get; }
- public void Clear()
- {
- lock (_list)
- {
- _list.Clear();
- }
- }
- public void Publish(object sender, TData data, Properties? properties = null)
- {
- if (data == null || _Socket ==null) return;
- _Socket.Send(this.GetMsg(data,properties).GetBytes());
- }
- public Task PublishAsync(object sender, TData data, Properties? properties = null)
- {
- if (data == null || _Socket == null) return Task.CompletedTask;
- return Task.Run(()=> _Socket.Send(this.GetMsg(data, properties).GetBytes()));
- }
- public Guid Subscrip(Action<object, EventArgs<TData>> action, Properties? properties = null)
- {
- lock (_list)
- {
- ArgumentNullException.ThrowIfNull(action);
- properties ??= Properties.Default;
- var temp = new ActionValue<TData>(action, properties);
- _list[temp.IntPtr] = temp;
- return temp.IntPtr;
- }
- }
- public void UnSubscrip(Guid guid)
- {
- lock (_list)
- {
- if (guid == Guid.Empty) return;
- _list.TryRemove(guid, out _);
- }
- }
- }
- }
|