コード例 #1
0
        public async Task Handle(Session session, Entity entity, IActorMessage actorRequest)
        {
            try
            {
                Request request = actorRequest as Request;
                if (request == null)
                {
                    Log.Error($"消息类型转换错误: {actorRequest.GetType().FullName} to {typeof (Request).Name}");
                    return;
                }
                E e = entity as E;
                if (e == null)
                {
                    Log.Error($"Actor类型转换错误: {entity.GetType().Name} to {typeof(E).Name}");
                    return;
                }

                int rpcId = request.RpcId;
                await this.Run(e, request, response =>
                {
                    // 等回调回来,session可以已经断开了,所以需要判断session id是否为0
                    if (session.IsDisposed)
                    {
                        return;
                    }
                    response.RpcId = rpcId;

                    session.Reply(response);
                });
            }
            catch (Exception e)
            {
                throw new Exception($"解释消息失败: {actorRequest.GetType().FullName}", e);
            }
        }
コード例 #2
0
        private void ProcessIActorMessageMessagePump(object state)
        {
            bool          useThreadPool = ((bool)state);
            IActorMessage msg           = null;

            _actorRegistered.WaitOne();
            _actorRegistered.Set();

            for (;;)
            {
                msg = GetNextMessage();

                if (ShouldExit())
                {
                    return;
                }

                if (null == msg)
                {
                    continue;
                }

                if (typeof(ControlMessages.HangUp) == msg.GetType())
                {
                    if (null != msg.Status && !msg.Status.Task.IsCompleted)
                    {
                        msg.Status.SetResult(msg);
                    }
                    //this.Disable();
                    return;
                }

                Interlocked.Increment(ref tellingCount);

                if (useThreadPool)
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(ProcessIActorMessageOnThreadPoolFcn), msg);
                }
                else
                {
                    IActor actor = null;

                    try
                    {
                        actor = GetActorForMessage(msg);

                        if (null == actor)
                        {
                            throw new NoActorForMessageTypeException(msg.GetType().FullName);
                        }

                        ProcessIActorMessage(ref actor, msg);
                    }
                    catch (Exception ex)
                    {
                        CheckForAndRunExceptionHandler(ex, actor, msg);
                    }
                }
            }
        }
コード例 #3
0
ファイル: AMActorHandler.cs プロジェクト: tuita520/ETServer
        public async Task Handle(Session session, Entity entity, IActorMessage actorRequest)
        {
            Message msg = actorRequest as Message;

            if (msg == null)
            {
                Log.Error($"消息类型转换错误: {actorRequest.GetType().FullName} to {typeof (Message).Name}");
                return;
            }
            E e = entity as E;

            if (e == null)
            {
                Log.Error($"Actor类型转换错误: {entity.GetType().Name} to {typeof(E).Name}");
                return;
            }

            int           rpcId    = actorRequest.RpcId;
            ActorResponse response = new ActorResponse
            {
                RpcId = rpcId
            };

            session.Reply(response);

            await this.Run(e, msg);
        }
コード例 #4
0
        public async Task Handle(Session session, Entity entity, IActorMessage actorRequest)
        {
            Message msg = actorRequest as Message;

            if (msg == null)
            {
                Log.Error($"消息类型转换错误: {actorRequest.GetType().FullName} to {typeof (Message).Name}");
                return;
            }
            E e = entity as E;

            if (e == null)
            {
                Log.Error($"Actor类型转换错误: {entity.GetType().Name} to {typeof(E).Name}");
                return;
            }

            await this.Run(e, msg);

            // 等回调回来,session可以已经断开了,所以需要判断session id是否为0
            if (session.IsDisposed)
            {
                return;
            }
            ActorResponse response = new ActorResponse
            {
                RpcId = actorRequest.RpcId
            };

            session.Reply(response);
        }
コード例 #5
0
        protected virtual IActor GetActorForMessage(IActorMessage msg)
        {
            IActor actor = null;

            _messageTypeToActor.TryGetValue(msg.GetType(), out actor);

            return(actor);
        }
コード例 #6
0
        public async Task Handle(Session session, Entity entity, IActorMessage actorRequest)
        {
            if (!this.handlers.TryGetValue(actorRequest.GetType(), out IMActorHandler handler))
            {
                throw new Exception($"not found message handler: {MongoHelper.ToJson(actorRequest)}");
            }

            await handler.Handle(session, entity, actorRequest);
        }
        /// <summary>
        /// 根据actor消息分发给ActorMessageHandler处理
        /// </summary>
        public static async Task Handle(this ActorMessageDispatherComponent self, Session session, Entity entity, IActorMessage actorRequest)
        {
            if (!self.ActorMessageHandlers.TryGetValue(actorRequest.GetType(), out IMActorHandler handler))
            {
                throw new Exception($"not found message handler: {Newtonsoft.Json.JsonConvert.SerializeObject(actorRequest)}");
            }

            await handler.Handle(session, entity, actorRequest);
        }
コード例 #8
0
        /// <summary>
        /// 根据actor消息分发给ActorMessageHandler处理
        /// </summary>
        public static async Task Handle(this ActorMessageDispatherComponent self, Session session, Entity entity, IActorMessage actorRequest)
        {
            if (!self.ActorMessageHandlers.TryGetValue(actorRequest.GetType(), out IMActorHandler handler))
            {
                throw new Exception($"not found message handler: {MongoHelper.ToJson(actorRequest)}");
            }

            await handler.Handle(session, entity, actorRequest);
        }
コード例 #9
0
        private void ProcessIActorMessageMessagePump()
        {
            IActorMessage msg = null;

            _typeRegistered.WaitOne();
            _typeRegistered.Set();

            for (; ;)
            {
                msg = GetNextMessage();

                if (ShouldExit())
                {
                    return;
                }

                if (null == msg)
                {
                    continue;
                }

                if (typeof(ControlMessages.HangUp) == msg.GetType())
                {
                    if (null != msg.Status && !msg.Status.Task.IsCompleted)
                    {
                        msg.Status.SetResult(msg);
                    }
                    return;
                }
                try
                {
                    string relayName = messageTypeToConnectionString[msg.GetType()];
                    IActor actor     = new RecieveResponseFromRequestByType(msg.GetType(), msg.GetType(), connectionString, relayName);

                    Interlocked.Increment(ref tellingCount);
                    Type msgType = msg.GetType();
                    actor.OnMessageRecieved(msg);
                }
                catch (Exception ex)
                {
                    //TODO CheckForAndRunExceptionHandler(ex, actor, msg);
                }
            }
        }
コード例 #10
0
        public void AddMessage(IActorMessage msg)
        {
            if (msg is ControlMessages.HangUp)
            {
                if (!recieveMessagesOnly)
                {
                    if (null != msg.Status && !msg.Status.Task.IsCompleted)
                    {
                        msg.Status.SetResult(msg);
                    }
                    return;
                }

                hangUp = (msg as ControlMessages.HangUp);
                Kill();
                return;
            }

            if (recieveMessagesOnly)
            {
                throw new Telegraphy.Net.OperatorCannotSendMessagesException();
            }

            // Serialize the message first
            try
            {
                if (msg is MsgType)
                {
                    SerializeAndSend(msg, Queue, (MsgType)msg);
                }
                else if ((msg as IActorMessage).Message is MsgType)
                {
                    SerializeAndSend(msg, Queue, (MsgType)(msg as IActorMessage).Message);
                }
                else
                {
                    throw new DontKnowHowToSerializeTypeException(msg.GetType().ToString());
                }

                if (null != msg.Status && !msg.Status.Task.IsCanceled)
                {
                    msg.Status.TrySetResult(msg);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.GetType() + ":" + ex.Message + ex.StackTrace);
                Exception foundEx = null;
                var       handler = this.FindExceptionHandler(_exceptionTypeToHandler, ex, out foundEx);

                if (null != handler)
                {
                    handler.Invoke(foundEx);
                }
            }
        }
コード例 #11
0
        private bool Serialize <T>(T msg, IActorMessage toSerialize, ushort version, byte[] messageBytes, byte[] resultBytes) where T : IActorMessage
        {
            // <verstion-short> (always Zero for this type of serializedMessage)
            // 16byte.message.guid
            // <size.of.type.in.Bytes-ushort>
            // <bytes.of.type.string-bytearray>
            // <size.of.message-uint>
            // <bytes.of.message-bytearray>
            // <size.of.result-uint>
            // <bytes.of.result-bytearray>
            // <status.flags-uint>

            uint serializedByteCount = IActorMessageSerializationActor.MinSizeOfSerializedMessage;

            var messageID = Guid.NewGuid().ToByteArray();

            byte[]       typeBytes  = null;
            uint         sizeOfType = 0;
            IFormatter   formatter  = new MessageTypeFormatter();
            MemoryStream typeMs     = new MemoryStream();

            formatter.Serialize(typeMs, toSerialize.GetType().AssemblyQualifiedName.ToString());
            typeBytes = typeMs.GetBuffer();
            typeMs    = null;
            // typeBytes = Encoding.UTF8.GetBytes(toSerialize.GetType().AssemblyQualifiedName);
            sizeOfType = (uint)typeBytes.Length;

            uint statusFlags = 0; //TODO:

            byte[] serializedMsg = CreateSerializationPackage(version, typeBytes, messageID, messageBytes, resultBytes, statusFlags);

            if (null != msg.Status)
            {
                if (!(msg.GetType() == typeof(SerializeMessage <IActorMessage>)))
                {
                    msg.Status.SetResult(new SerializeMessage <IActorMessage>(toSerialize, serializedMsg));
                }
                else
                {
                    msg.ProcessingResult = serializedMsg;
                    msg.Status.SetResult(msg);
                }
            }
            else
            {
                msg.ProcessingResult = serializedMsg;
            }

            return(true);
        }
コード例 #12
0
        public void AddMessage(IActorMessage msg)
        {
            if (msg is ControlMessages.HangUp)
            {
                if (!recieveMessagesOnly)
                {
                    if (null != msg.Status && !msg.Status.Task.IsCompleted)
                    {
                        msg.Status.SetResult(msg);
                    }
                    return;
                }

                hangUp = (msg as ControlMessages.HangUp);
                Kill();
                return;
            }

            if (recieveMessagesOnly)
            {
                throw new Telegraphy.Net.OperatorCannotSendMessagesException(msg.GetType().ToString());
            }

            // TODO allow the serializers to be passed in as IActors
            // Serialize the message first
            try
            {
                SerializeAndSend(msg, queue);

                if (null != msg.Status && !msg.Status.Task.IsCanceled)
                {
                    msg.Status.TrySetResult(msg);
                }
            }
            catch (Exception ex)
            {
                Exception foundEx = null;
                var       handler = this.FindExceptionHandler(_exceptionTypeToHandler, ex, out foundEx);

                if (null != handler)
                {
                    handler.Invoke(foundEx);
                }
            }
        }
コード例 #13
0
        private void ProcessIActorMessageOnThreadPoolFcn(object state)
        {
            try
            {
                if (null != _concurrentThreadLock)
                {
                    _concurrentThreadLock.WaitOne();
                }

                if (ShouldExit())
                {
                    return;
                }

                IActorMessage msg   = ((IActorMessage)state);
                IActor        actor = null;

                try
                {
                    actor = GetActorForMessage(msg);

                    if (null == actor)
                    {
                        throw new NoActorForMessageTypeException(msg.GetType().FullName);
                    }

                    ProcessIActorMessage(ref actor, msg);
                }
                catch (Exception ex)
                {
                    CheckForAndRunExceptionHandler(ex, actor, msg);
                }
            }
            finally
            {
                if (null != _concurrentThreadLock)
                {
                    _concurrentThreadLock.Release();
                }
            }
        }
コード例 #14
0
        public static void BroadcastRoom(long roonId, IActorMessage message, params long[] filterUids)
        {
            Room room = Game.Scene.GetComponent <RoomComponent>().Get(roonId);

            if (room == null)
            {
                Log.Error($"{message?.GetType()?.ToString()} Broadcast 失敗! 找不到Room : {roonId}");
                return;
            }
            List <MapUnit> targets = room.GetAll();
            ActorMessageSenderComponent actorLocationSenderComponent = Game.Scene.GetComponent <ActorMessageSenderComponent>();

            for (int i = 0; i < targets.Count; i++)
            {
                if (filterUids != null)
                {
                    bool isFilter = false;
                    for (int k = 0; k < filterUids.Length; k++)
                    {
                        if (targets[i].Uid == filterUids[k])
                        {
                            isFilter = true;
                            break;
                        }
                    }
                    if (isFilter)
                    {
                        continue;
                    }
                }

                if (!CheckMapUnitSenderVailed(targets[i], out var gateSessionActorId))
                {
                    continue;
                }

                ActorMessageSender actorMessageSender = actorLocationSenderComponent.Get(gateSessionActorId);
                actorMessageSender.Send(message);
            }
        }
コード例 #15
0
        private static byte[] GetBytesFromType(Type MsgType, IActorMessage msg)
        {
            byte[] msgBytes = null;
            if (MsgType == typeof(string))
            {
                System.Diagnostics.Debug.WriteLine("Serializing " + (string)(msg as IActorMessage).Message);
                if ((msg as IActorMessage).Message.GetType().Name.Equals("String"))
                {
                    msgBytes = Encoding.UTF8.GetBytes((string)(msg as IActorMessage).Message);
                }
                else
                {
                    throw new NotConfiguredToSerializeThisTypeOfMessageException("String");
                }
            }
            else if (MsgType == typeof(byte[]))
            {
                if ((msg as IActorMessage).Message.GetType().Name.Equals("Byte[]"))
                {
                    msgBytes = (byte[])(msg as IActorMessage).Message;
                }
                else
                {
                    throw new NotConfiguredToSerializeThisTypeOfMessageException("Byte[]");
                }
            }
            else if (MsgType == msg.GetType())
            {
                return(null);
            }
            else if (MsgType == (msg as IActorMessage).Message.GetType() && (msg as IActorMessage).Message is System.Runtime.Serialization.ISerializable)
            {
                var serializeTask = Telegraph.Instance.Ask(new SerializeMessage <System.Runtime.Serialization.ISerializable>((System.Runtime.Serialization.ISerializable)(msg as IActorMessage).Message));
                msgBytes = (serializeTask.Result.ProcessingResult as byte[]);
            }

            return(msgBytes);
        }
コード例 #16
0
        public void AddMessage(IActorMessage msg)
        {
            if (msg is ControlMessages.HangUp)
            {
                if (!recieveMessagesOnly)
                {
                    if (null != msg.Status && !msg.Status.Task.IsCompleted)
                    {
                        msg.Status.SetResult(msg);
                    }
                    return;
                }

                hangUp = (msg as ControlMessages.HangUp);
                Kill();
                return;
            }

            if (recieveMessagesOnly)
            {
                throw new Telegraphy.Net.OperatorCannotSendMessagesException();
            }

            if (!(msg is EmailMsg))
            {
                throw new UnsupportedMessageException("Outlook Email Operators only support the EmailMsg type. They do not support " + msg.GetType());
            }

            try
            {
                SendEmail((EmailMsg)msg, this.emailAddress, this.password, this.fromFriendlyName);

                if (null != msg.Status && !msg.Status.Task.IsCanceled)
                {
                    msg.Status.TrySetResult(msg);
                }
            }
            catch (Exception ex)
            {
                Exception foundEx = null;
                var       handler = this.FindExceptionHandler(_exceptionTypeToHandler, ex, out foundEx);

                if (null != handler)
                {
                    handler.Invoke(foundEx);
                }

                if (null != msg.Status && !msg.Status.Task.IsCanceled)
                {
                    msg.Status.TrySetException(ex);
                }
            }
        }
コード例 #17
0
        private void CheckForAndRunExceptionHandler(Exception ex, IActor actor, IActorMessage msg)
        {
            List <Exception> exceptions = new List <Exception>();

            if (null != ex)
            {
                exceptions.Add(ex);
            }

            try
            {
                Exception foundEx = null;
                Func <Exception, IActor, IActorMessage, IActorInvocation, IActor> handler;

                handler = this.FindExceptionHandler(_exceptionTypeToHandler, ex, actor, msg, out foundEx);
                if (null != foundEx && foundEx != ex)
                {
                    exceptions.Add(foundEx);
                }

                if (null == handler)
                {
                    return;
                }

                IActorInvocation invoker  = null;
                IActor           newActor = handler.Invoke(foundEx, actor, msg, invoker);

                if (null == newActor || newActor == actor)
                {
                    return;
                }

                _messageTypeToActor.TryUpdate(msg.GetType(), newActor, actor);
            }
            catch (NotImplementedException ne)
            {
                exceptions.Add(ne);
                Console.Error.WriteLine(ne);
                System.Diagnostics.Debug.Assert(false);
                throw;
            }
            catch (Exception exp)
            {
                exceptions.Add(exp);
                Console.Error.WriteLine(exp);
                //TODO fail hard!!!
                System.Diagnostics.Debug.Assert(false);
            }
            finally
            {
                if (null != msg.Status && exceptions.Any())
                {
                    try
                    {
                        msg.Status.SetException(exceptions);
                    }
                    catch (System.InvalidOperationException)
                    {
                        // The underlying System.Threading.Tasks.Task`1 is already in one of the three final
                        //     states: System.Threading.Tasks.TaskStatus.RanToCompletion, System.Threading.Tasks.TaskStatus.Faulted,
                        //     or System.Threading.Tasks.TaskStatus.Canceled.
                    }
                }
            }
        }