首页 技术 正文
技术 2022年11月15日
0 收藏 400 点赞 4,743 浏览 16474 个字

原文网址: http://www.cnblogs.com/csdev

Networkcomms 是一款C# 语言编写的TCP/UDP通信框架  作者是英国人  以前是收费的 目前作者已经开源  许可是:Apache License v2

开源地址是:https://github.com/MarcFletcher/NetworkComms.Net

连接监听器基类

 /// <summary>    /// A base class that the listener of each connection type inherits from.    /// This allows NetworkComms.Net to manage listeners at the general connection level.    /// 连接监听器基类    /// </summary>    public abstract class ConnectionListenerBase    {        #region Public Properties        /// <summary>        /// The send receive options associated with this listener.        /// 监听器使用的收发参数类        /// </summary>        public SendReceiveOptions ListenerDefaultSendReceiveOptions { get; protected set; }        /// <summary>        /// The connection type that this listener supports.        /// 连接类型        /// </summary>        public ConnectionType ConnectionType { get; protected set; }        /// <summary>        /// The application layer protocol status for this listener.        /// 应用层协议        /// </summary>        public ApplicationLayerProtocolStatus ApplicationLayerProtocol { get; protected set; }        /// <summary>        /// True if this listener is listening.        /// 是否在监听中        /// </summary>        public bool IsListening { get; protected set; }        /// <summary>        /// True if this listener will be advertised via peer discovery        /// 设置为True  则可以通过Peer discovery被发现        /// </summary>        public bool IsDiscoverable { get; protected set; }        /// <summary>        /// The local IPEndPoint that this listener is associated with.        /// 本地IP端点        /// </summary>        public EndPoint LocalListenEndPoint { get; protected set; }        #endregion        #region Private Properties        /// <summary>        /// Thread safety locker which is used when accessing <see cref="incomingPacketHandlers"/>        /// and <see cref="incomingPacketUnwrappers"/>        /// 同步锁  用于线程安全        /// </summary>        private object delegateLocker = new object();        /// <summary>        /// By default all incoming objects are handled using ListenerDefaultSendReceiveOptions. Should the user want something else        /// those settings are stored here        ///字典  用于存储 ( 消息类型与 数据包展开器)        /// 数据包展开器的作用是 对应消息类型与收发参数类        /// </summary>        private Dictionary<string, PacketTypeUnwrapper> incomingPacketUnwrappers = new Dictionary<string, PacketTypeUnwrapper>();        /// <summary>        /// A listener specific incoming packet handler dictionary. These are called before any global handlers        ///字典  用于存储  ( 消息类型  与对应的处理器列表)        /// </summary>        private Dictionary<string, List<IPacketTypeHandlerDelegateWrapper>> incomingPacketHandlers = new Dictionary<string, List<IPacketTypeHandlerDelegateWrapper>>();        #endregion        /// <summary>        /// Create a new listener instance        /// 创建一个监听器实例        /// </summary>        /// <param name="connectionType">连接类型 The connection type to listen for.</param>        /// <param name="sendReceiveOptions">收发参数  The send receive options to use for this listener</param>        /// <param name="applicationLayerProtocol">应用层协议  If enabled NetworkComms.Net uses a custom        /// application layer protocol to provide useful features such as inline serialisation,        /// transparent packet transmission, remote peer handshake and information etc. We strongly        /// recommend you enable the NetworkComms.Net application layer protocol.</param>        /// <param name="allowDiscoverable">是否允许被其他端点发现  Determines if the newly created <see cref="ConnectionListenerBase"/> will be discoverable if <see cref="Tools.PeerDiscovery"/> is enabled.</param>        protected ConnectionListenerBase(ConnectionType connectionType,            SendReceiveOptions sendReceiveOptions,            ApplicationLayerProtocolStatus applicationLayerProtocol,            bool allowDiscoverable)        {            if (connectionType == ConnectionType.Undefined) throw new ArgumentException("ConnectionType.Undefined is not valid when calling this method.", "connectionType");            if (sendReceiveOptions == null) throw new ArgumentNullException("sendReceiveOptions", "Provided send receive option may not be null.");            if (applicationLayerProtocol == ApplicationLayerProtocolStatus.Undefined) throw new ArgumentException("ApplicationLayerProtocolStatus.Undefined is not valid when calling this method.", "applicationLayerProtocol");            //Validate SRO options if the application layer protocol is disabled            //如果应用层协议禁用 验证收发参数类            if (applicationLayerProtocol == ApplicationLayerProtocolStatus.Disabled)            {                if (sendReceiveOptions.Options.ContainsKey("ReceiveConfirmationRequired"))                    throw new ArgumentException("Attempted to create an unmanaged connection when the provided send receive" +                        " options specified the ReceiveConfirmationRequired option. Please provide compatible send receive options in order to successfully" +                        " instantiate this unmanaged connection.", "sendReceiveOptions");                if (sendReceiveOptions.DataSerializer != DPSManager.GetDataSerializer<NullSerializer>())                    throw new ArgumentException("Attempted to create an unmanaged connection when the provided send receive" +                        " options serialiser was not NullSerializer. Please provide compatible send receive options in order to successfully" +                        " instantiate this unmanaged connection.", "sendReceiveOptions");                )                    throw new ArgumentException("Attempted to create an unmanaged connection when the provided send receive" +                        " options contains data processors. Data processors may not be used with unmanaged connections." +                        " Please provide compatible send receive options in order to successfully instantiate this unmanaged connection.", "sendReceiveOptions");            }            if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Info("Created new connection listener (" + connectionType.ToString() + "-" + (applicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? "E" : "D") + ").");            this.ConnectionType = connectionType;            this.ListenerDefaultSendReceiveOptions = sendReceiveOptions;            this.ApplicationLayerProtocol = applicationLayerProtocol;            this.IsDiscoverable = allowDiscoverable;        }        /// <summary>        /// Returns a clean string containing the current listener state        /// 返回当前监听器的监听状态        /// </summary>        /// <returns></returns>        public override string ToString()        {            string returnString = "[" + ConnectionType.ToString() + "-" + (ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? "E" : "D") + "] ";            if (IsListening && LocalListenEndPoint != null)                return returnString + "Listening - " + LocalListenEndPoint.ToString();            else                return returnString + "Not Listening";        }        #region Start and Stop Listening        /// <summary>        /// Start listening for incoming connections.        /// 开始监听进入的连接        /// </summary>        /// <param name="desiredLocalListenEndPoint">Try to start listening on this EndPoint.</param>        /// <param name="useRandomPortFailOver">If the request EndPoint is unavailable fail over to a random port.</param>        internal abstract void StartListening(EndPoint desiredLocalListenEndPoint, bool useRandomPortFailOver);        /// <summary>        /// Stop listening for incoming connections.        /// 停止监听        /// </summary>        internal abstract void StopListening();        #endregion        #region Listener Specific Packet Handlers        /// <summary>        /// Append a listener specific packet handler using the listener default SendReceiveOptions        /// 添加一个监听器指定的数据包处理器  使用默认的收发参数        /// </summary>        /// <typeparam name="incomingObjectType">The type of incoming object</typeparam>        /// <param name="packetTypeStr">The packet type for which this handler will be executed</param>        /// <param name="packetHandlerDelgatePointer">The delegate to be executed when a packet of packetTypeStr is received</param>        public void AppendIncomingPacketHandler<incomingObjectType>(string packetTypeStr, NetworkComms.PacketHandlerCallBackDelegate<incomingObjectType> packetHandlerDelgatePointer)        {            AppendIncomingPacketHandler<incomingObjectType>(packetTypeStr, packetHandlerDelgatePointer, ListenerDefaultSendReceiveOptions);        }        /// <summary>        /// Append a listener specific packet handler        /// 添加一个监听器指定的数据包处理器  使用指定的收发参数        /// </summary>        /// <typeparam name="incomingObjectType">进入的数据  The type of incoming object</typeparam>        /// <param name="packetTypeStr">消息类型  The packet type for which this handler will be executed</param>        /// <param name="packetHandlerDelgatePointer">处理器 The delegate to be executed when a packet of packetTypeStr is received</param>        /// <param name="options">收发参数  The <see cref="SendReceiveOptions"/> to be used for the provided packet type</param>        public void AppendIncomingPacketHandler<incomingObjectType>(string packetTypeStr, NetworkComms.PacketHandlerCallBackDelegate<incomingObjectType> packetHandlerDelgatePointer, SendReceiveOptions options)        {            if (packetTypeStr == null) throw new ArgumentNullException("packetTypeStr", "Provided packetType string cannot be null.");            if (packetHandlerDelgatePointer == null) throw new ArgumentNullException("packetHandlerDelgatePointer", "Provided NetworkComms.PacketHandlerCallBackDelegate<incomingObjectType> cannot be null.");            if (options == null) throw new ArgumentNullException("options", "Provided SendReceiveOptions cannot be null.");            //If we are adding a handler for an unmanaged packet type the data serializer must be NullSerializer            //Checks for unmanaged packet types            //如果我们给“非托管”的数据类型添加序列化器,必须是NullSerializer            //检查“非托管”数据包类型    “非托管”主要在与其他语言的通信场景中使用            if (packetTypeStr == Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.Unmanaged))            {                if (options.DataSerializer != DPSManager.GetDataSerializer<NullSerializer>())                    throw new ArgumentException("Attempted to add packet handler for an unmanaged packet type when the provided send receive options serializer was not NullSerializer.");                )                    throw new ArgumentException("Attempted to add packet handler for an unmanaged packet type when the provided send receive options contains data processors. Data processors may not be used inline with unmanaged packet types.");            }            lock (delegateLocker)            {                if (incomingPacketUnwrappers.ContainsKey(packetTypeStr))                {                    //Make sure if we already have an existing entry that it matches with the provided                    //如果收发参数前后不一致 抛出异常                    if (!incomingPacketUnwrappers[packetTypeStr].Options.OptionsCompatible(options))                        throw new PacketHandlerException("The provided SendReceiveOptions are not compatible with existing SendReceiveOptions already specified for this packetTypeStr.");                }                else                    incomingPacketUnwrappers.Add(packetTypeStr, new PacketTypeUnwrapper(packetTypeStr, options));                //Ad the handler to the list                //添加处理器到列表中                if (incomingPacketHandlers.ContainsKey(packetTypeStr))                {                    //Make sure we avoid duplicates                    //确保不重复                    PacketTypeHandlerDelegateWrapper<incomingObjectType> toCompareDelegate = new PacketTypeHandlerDelegateWrapper<incomingObjectType>(packetHandlerDelgatePointer);                    bool delegateAlreadyExists = false;                    foreach (var handler in incomingPacketHandlers[packetTypeStr])                    {                        if (handler == toCompareDelegate)                        {                            delegateAlreadyExists = true;                            break;                        }                    }                    if (delegateAlreadyExists)                        throw new PacketHandlerException("This specific packet handler delegate already exists for the provided packetTypeStr.");                    incomingPacketHandlers[packetTypeStr].Add(new PacketTypeHandlerDelegateWrapper<incomingObjectType>(packetHandlerDelgatePointer));                }                else                    incomingPacketHandlers.Add(packetTypeStr, new List<IPacketTypeHandlerDelegateWrapper>() { new PacketTypeHandlerDelegateWrapper<incomingObjectType>(packetHandlerDelgatePointer) });                if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Info("Added listener specific incoming packetHandler for '" + packetTypeStr + "' packetType on listener " + ToString());            }        }        /// <summary>        /// Append a listener specific unmanaged packet handler        /// 为“非托管”数据包添加处理器        /// </summary>        /// <param name="packetHandlerDelgatePointer">The delegate to be executed when an unmanaged packet is received</param>        public void AppendIncomingUnmanagedPacketHandler(NetworkComms.PacketHandlerCallBackDelegate<byte[]> packetHandlerDelgatePointer)        {            AppendIncomingPacketHandler<byte[]>(Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.Unmanaged), packetHandlerDelgatePointer, new SendReceiveOptions<NullSerializer>());        }        /// <summary>        /// Returns true if an unmanaged packet handler exists on this listener        /// 如果“非托管”数据包存在对应的处理器 返回True        /// </summary>        /// <param name="packetTypeStr">The packet type for which to check incoming packet handlers</param>        /// <returns>True if a packet handler exists</returns>        public bool IncomingPacketHandlerExists(string packetTypeStr)        {            lock (delegateLocker)                return incomingPacketHandlers.ContainsKey(packetTypeStr);        }        /// <summary>        /// Returns true if a listener specific unmanaged packet handler exists, on this listener.        /// 如果监听器指定的“未托管”数据包处理器存在  返回True        /// </summary>        /// <returns>True if an unmanaged packet handler exists</returns>        public bool IncomingUnmanagedPacketHandlerExists()        {            lock (delegateLocker)                return incomingPacketHandlers.ContainsKey(Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.Unmanaged));        }        /// <summary>        /// Returns true if the provided listener specific packet handler has been added for the provided packet type, on this listener.        /// 如果某消息类型 对应的处理器已经存在 返回True        /// </summary>        /// <param name="packetTypeStr">消息类型  The packet type within which to check packet handlers</param>        /// <param name="packetHandlerDelgatePointer">处理器  The packet handler to look for</param>        /// <returns>True if a listener specific packet handler exists for the provided packetType</returns>        public bool IncomingPacketHandlerExists(string packetTypeStr, Delegate packetHandlerDelgatePointer)        {            lock (delegateLocker)            {                if (incomingPacketHandlers.ContainsKey(packetTypeStr))                {                    foreach (var handler in incomingPacketHandlers[packetTypeStr])                        if (handler.EqualsDelegate(packetHandlerDelgatePointer))                            return true;                }            }            return false;        }        /// <summary>        /// Returns true if the provided listener specific unmanaged packet handler has been added, on this listener.        ///  如果“未托管”数据包对应的处理器已经存在 返回True        /// </summary>        /// <param name="packetHandlerDelgatePointer">The packet handler to look for</param>        /// <returns>True if a listener specific unmanaged packet handler exists</returns>        public bool IncomingUnmanagedPacketHandlerExists(Delegate packetHandlerDelgatePointer)        {            lock (delegateLocker)            {                if (incomingPacketHandlers.ContainsKey(Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.Unmanaged)))                {                    foreach (var handler in incomingPacketHandlers[Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.Unmanaged)])                        if (handler.EqualsDelegate(packetHandlerDelgatePointer))                            return true;                }            }            return false;        }        /// <summary>        /// Remove the provided listener specific packet handler for the specified packet type, on this listener.        /// 根据参数中的消息类型 删除相应的处理器        /// </summary>        /// <param name="packetTypeStr">消息类型  Packet type for which this delegate should be removed</param>        /// <param name="packetHandlerDelgatePointer">处理器  The delegate to remove</param>        public void RemoveIncomingPacketHandler(string packetTypeStr, Delegate packetHandlerDelgatePointer)        {            lock (delegateLocker)            {                if (incomingPacketHandlers.ContainsKey(packetTypeStr))                {                    //Remove any instances of this handler from the delegates                    //The bonus here is if the delegate has not been added we continue quite happily                    //从委托列表中删除这个处理器的任何实例                    //如果处理器尚未添加也很好                    IPacketTypeHandlerDelegateWrapper toRemove = null;                    foreach (var handler in incomingPacketHandlers[packetTypeStr])                    {                        if (handler.EqualsDelegate(packetHandlerDelgatePointer))                        {                            toRemove = handler;                            break;                        }                    }                    if (toRemove != null)                        incomingPacketHandlers[packetTypeStr].Remove(toRemove);                    )                    {                        incomingPacketHandlers.Remove(packetTypeStr);                        //Remove any entries in the unwrappers dict as well as we are done with this packetTypeStr                        //从字典中删除相应消息的处理器                        if (incomingPacketHandlers.ContainsKey(packetTypeStr))                            incomingPacketHandlers.Remove(packetTypeStr);                        if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Info("Removed a listener specific packetHandler for '" + packetTypeStr + "' packetType. No handlers remain on listener " + ToString());                    }                    else                        if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Info("Removed a listener specific packetHandler for '" + packetTypeStr + "' packetType. Handlers remain on listener " + ToString());                }            }        }        /// <summary>        /// Remove the provided listener specific unmanaged packet handler, on this listener.        /// 删除“为托管”数据包处理器        /// </summary>        /// <param name="packetHandlerDelgatePointer">The delegate to remove</param>        public void RemoveIncomingUnmanagedPacketHandler(Delegate packetHandlerDelgatePointer)        {            RemoveIncomingPacketHandler(Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.Unmanaged), packetHandlerDelgatePointer);        }        /// <summary>        /// Removes all listener specific packet handlers for the provided packet type, on this listener.        /// 根据消息类型 删除处理器        /// </summary>        /// <param name="packetTypeStr">消息类型   Packet type for which all delegates should be removed</param>        public void RemoveIncomingPacketHandler(string packetTypeStr)        {            lock (delegateLocker)            {                //We don't need to check for potentially removing a critical reserved packet handler here because those cannot be removed.                if (incomingPacketHandlers.ContainsKey(packetTypeStr))                {                    incomingPacketHandlers.Remove(packetTypeStr);                    if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Info("Removed all listener specific incoming packetHandlers for '" + packetTypeStr + "' packetType on listener " + ToString());                }            }        }        /// <summary>        /// Removes all unmanaged packet handlers, on this listener.        /// 删除所有的“为托管”数据包处理器        /// </summary>        public void RemoveIncomingUnmanagedPacketHandler()        {            RemoveIncomingPacketHandler(Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.Unmanaged));        }        /// <summary>        /// Removes all packet handlers for all packet types, on this listener.        /// 删除所有的数据包处理器        /// </summary>        public void RemoveIncomingPacketHandler()        {            lock (delegateLocker)            {                incomingPacketHandlers = new Dictionary<string, List<IPacketTypeHandlerDelegateWrapper>>();                if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Info("Removed all listener specific incoming packetHandlers for all packetTypes on listener " + ToString());            }        }        /// <summary>        /// Add all listener specific packet handlers to the provided connection        /// 添加所有的数据包处理器到指定的连接上        /// </summary>        /// <param name="connection">连接  The connection to which packet handlers should be added</param>        internal void AddListenerPacketHandlersToConnection(Connection connection)        {            lock (delegateLocker)            {                foreach (string packetType in incomingPacketHandlers.Keys)                {                    foreach (IPacketTypeHandlerDelegateWrapper handler in incomingPacketHandlers[packetType])                        connection.AppendIncomingPacketHandler(packetType, handler, incomingPacketUnwrappers[packetType].Options);                }            }            if (NetworkComms.LoggingEnabled) NetworkComms.Logger.Info("Appended connection specific packet handlers from listener '" + ToString() + "' to connection '" + connection.ToString() + "'.");        }        #endregion    }
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,086
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,561
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,411
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,184
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,820
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,904