Exemplo n.º 1
0
        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="e">接收数据</param>
        /// <param name="server">服务端</param>
        public static void Listener <TPackageParse>(AsyncSocketTokenEventArgs e, AsyncSocketServer server) where TPackageParse : INetPackageParse, new()
        {
            try {
                IList <INetPackage> packages = Singleton <TPackageParse> .Instance().Parse(e, AsyncSocketServerReceive.LittleEndian, AsyncSocketServerReceive.MaxPackageSize);

                if (packages == null)
                {
                    server.Disconnect(e.ConnectionID);
                    if (AsyncSocketServerReceive.ErrorMsg != null)
                    {
                        AsyncSocketServerReceive.ErrorMsg.BeginInvoke("超出最大包大小:" + AsyncSocketServerReceive.MaxPackageSize.ToString() + ",连接被强行断开!", null, null);
                    }
                }
                else
                {
                    foreach (INetPackage package in packages)
                    {
                        if (package != null)
                        {
                            if (serverEvents.ContainsKey(package.Command))
                            {
                                serverEvents[package.Command].Process(package, e.ConnectionID, server);
                            }
                            else if (AsyncSocketServerReceive.ErrorMsg != null)
                            {
                                AsyncSocketServerReceive.ErrorMsg.BeginInvoke(package.Command.ToString() + "指令不存在!", null, null);
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                if (AsyncSocketServerReceive.ErrorMsg != null)
                {
                    AsyncSocketServerReceive.ErrorMsg.BeginInvoke(ex.Message, null, null);
                }
            }
        }