using HslCommunication.Core.Net; using System; using System.Collections.Generic; using System.Linq; using System.Text; using HslCommunication.Core; namespace HslCommunication.Enthernet { /// /// 订阅分类的核心组织对象 /// public class PushGroupClient : IDisposable { #region Constructor /// /// 实例化一个默认的对象 /// public PushGroupClient() { appSessions = new List( ); simpleHybird = new SimpleHybirdLock( ); } #endregion #region Public Method /// /// 新增一个订阅的会话 /// /// 会话 public void AddPushClient(AppSession session) { simpleHybird.Enter( ); appSessions.Add( session ); simpleHybird.Leave( ); } /// /// 移除一个订阅的会话 /// /// 客户端唯一的ID信息 public bool RemovePushClient( string clientID ) { bool result = false; simpleHybird.Enter( ); for (int i = 0; i < appSessions.Count; i++) { if(appSessions[i].ClientUniqueID == clientID) { appSessions[i].WorkSocket?.Close( ); appSessions.RemoveAt( i ); result = true; break; } } simpleHybird.Leave( ); return result; } /// /// 使用固定的发送方法将数据发送出去 /// /// 数据内容 /// 指定的推送方法 public void PushString( string content, Action send ) { simpleHybird.Enter( ); System.Threading.Interlocked.Increment( ref pushTimesCount ); for (int i = 0; i < appSessions.Count; i++) { send( appSessions[i], content ); } simpleHybird.Leave( ); } /// /// 移除并关闭所有的客户端 /// public int RemoveAllClient( ) { int result = 0; simpleHybird.Enter( ); for (int i = 0; i < appSessions.Count; i++) { appSessions[i].WorkSocket?.Close( ); } result = appSessions.Count; appSessions.Clear( ); simpleHybird.Leave( ); return result; } /// /// 获取是否推送过数据 /// /// True代表有,False代表没有 public bool HasPushedContent( ) { return pushTimesCount > 0L; } #endregion #region Private Member private List appSessions; // 所有的客户端信息 private SimpleHybirdLock simpleHybird; // 列表的锁 private long pushTimesCount = 0L; // 推送的次数总和 #endregion #region IDisposable Support private bool disposedValue = false; // 要检测冗余调用 /// /// 释放当前的程序所占用的资源 /// /// 是否释放资源 protected virtual void Dispose( bool disposing ) { if (!disposedValue) { if (disposing) { // TODO: 释放托管状态(托管对象)。 } // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。 // TODO: 将大型字段设置为 null。 simpleHybird.Enter( ); appSessions.ForEach( m => m.WorkSocket?.Close( ) ); appSessions.Clear( ); simpleHybird.Leave( ); simpleHybird.Dispose( ); disposedValue = true; } } // TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。 // ~PushGroupClient() { // // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。 // Dispose(false); // } // 添加此代码以正确实现可处置模式。 /// /// 释放当前的对象所占用的资源 /// public void Dispose() { // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。 Dispose( true ); // TODO: 如果在以上内容中替代了终结器,则取消注释以下行。 // GC.SuppressFinalize(this); } #endregion #region Object Override /// /// 获取本对象的字符串表示形式 /// /// public override string ToString() { return "PushGroupClient"; } #endregion } }