1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- using EventBus;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace TcpEventBus
- {
- public class TcpAnonymousEventData : IAnonymousEventData,ISubscripData
- {
- ConcurrentDictionary<Guid, ActionValue<object[]>> _list = new ConcurrentDictionary<Guid, ActionValue<object[]>>();
- private ISocket _Socket;
- public TcpAnonymousEventData(ISocket socket, string eventName, string hash)
- {
- _Socket = socket;
- EventName = eventName;
- Hash = hash;
- }
- public string EventName { get; }
- public string Hash { get; }
- public bool IsResultEvent => false;
- public bool IsAnonymous => true;
- public void Clear()
- {
- lock (_list)
- {
- _list.Clear();
- }
- }
- public void Publish(object sender, Properties? properties = null, params object[] data)
- {
- if (data == null || _Socket == null) return;
- _Socket.Send(this.GetAnonyMsg(data, properties).GetBytes());
- }
- public Task PublishAsync(object sender, Properties? properties = null, params object[] data)
- {
- if (data == null || _Socket == null) return Task.CompletedTask;
- return Task.Run(()=> _Socket.Send(this.GetAnonyMsg(data, properties).GetBytes()));
- }
- public Guid Subscrip(Action<object, EventArgs<object[]>> action, Properties? properties = null)
- {
- lock (_list)
- {
- ArgumentNullException.ThrowIfNull(action);
- properties ??= Properties.Default;
- var temp = new ActionValue<object[]>(action, properties);
- _list[temp.IntPtr] = temp;
- return temp.IntPtr;
- }
- }
- public void Subscrip(byte[] data, Properties properties)
- {
- lock (_list)
- {
- object[] t = MsgTool.GetAnonyDatas(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<object[]>(t, x.IntPtr, this)));
- }
- }
- public void SubscripData(byte[] data, Properties properties)
- {
- throw new NotImplementedException();
- }
- public void UnSubscrip(Guid guid)
- {
- lock (_list)
- {
- if (guid == Guid.Empty) return;
- _list.TryRemove(guid, out _);
- }
- }
- }
- }
|