Ejemplo n.º 1
0
        /// <summary>
        /// 服务接收消息处理函数
        /// </summary>
        /// <param name="header"></param>
        /// <param name="BodyBytes"></param>
        /// <param name="Socket"></param>
        private void Service_ReceiveMessage(Header header, byte[] BodyBytes, NetMQSocket Socket)
        {
            //初始化Model,并在会话结束后dispose
            using (var dbContext = new EntityModel())
            {
                Entity.Model.SessionEntity session = null;
                if (header.Session != null)
                {
                    session = dbContext.SessionEntities.FirstOrDefault(j => j.GUID == header.Session && j.ExpirationTime <= DateTime.Now);
                }

                IUser user;
                if (session == null)
                {
                    //没有登陆的话,分配一个游客账户
                    user = dbContext.UserEntities.FirstOrDefault(i => i.UserName == "Guest");
                }
                else
                {
                    //刷新session有效期
                    session.ExpirationTime = DateTime.Now.AddHours(1);
                    user = session.User;
                }

                if (user == null)
                {
                    Logger.Error($"Service Receive Error : User is Null !!!");
                    return;
                }

                //创建一个简单的会话上下文
                var context   = Context.CreateContext(user, header, dbContext, Socket);
                var eventArgs = new RequestEventArgs()
                {
                    Context = context
                };
                RequestEvent?.Invoke(this, eventArgs);
                if (eventArgs.Cancel == true)//如果接收的请求被取消,则不委托执行
                {
                    return;
                }
                try
                {
                    //交给注册的委托
                    var handle = MessageHandle.GetHandle(context.Header.MessageType);
                    if (handle != null)
                    {
                        handle.Invoke(context, BodyBytes);//全程务必保持由当前线程同步执行
                    }
                    else
                    {
                        Logger.Warn($"未注册的委托 : {context.Header.MessageType}");
                    }
                }
                catch (Exception ex)
                {
                    if (context._answer == false)
                    {
                        context.Response(new ResException(ex));
                    }
                }


                dbContext.SaveChanges();
            }
        }