Exemple #1
0
 /// <summary>
 /// 添加一个处理接收到的消息的监听器
 /// </summary>
 /// <param name="onEventReceived">OnEventReceived 委托的实现</param>
 public void AddEventListener(OnEventReceived onEventReceived)
 {
     SpaceBattle.OnEventCall += delegate(byte eventCode, object content, int senderId)
     {
         onEventReceived(eventCode, content);
     };
 }
Exemple #2
0
        /// <summary>
        /// Вызывает нужный метод-обработчик на основе типа события из БД
        /// </summary>
        private void HandleDbNotification(object sender, NpgsqlNotificationEventArgs?e)
        {
            _logger.LogTrace($"Получено новое событие от БД {GetDbLogName()}: " +
                             $"PID = {e?.PID}, " +
                             $"Channel = \"{e?.Channel}\", " +
                             $"Payload = \"{e?.Payload}\"");

            if (!String.IsNullOrEmpty(e?.Channel) && _eventsToSubscribe.Contains(e.Channel))
            {
                try
                {
                    _logger.LogTrace($"Вызов обработчика для события от БД {GetDbLogName()} с PID = {e.PID} (channel = \"{e.Channel}\")...");
                    OnEventReceived?.Invoke(this, new DbEvent(_dbOptions, e.Channel, e.Payload));
                    _logger.LogTrace($"Вызов обработчика для события от БД {GetDbLogName()} с PID = {e.PID} (channel = \"{e.Channel}\") завершен");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"Необработанное исключение при вызове обработка события от БД {GetDbLogName()} с PID = {e.PID} (channel = \"{e.Channel}\")");
                }
            }
            else
            {
                _logger.LogTrace($"Нет обработчиков для события из БД {GetDbLogName()} c PID = {e?.PID} (channel = \"{e?.Channel}\")");
            }
        }
Exemple #3
0
        private void EventLoop()
        {
            var task = _proxy.ExecuteRequestAsync(new Request
            {
                Uri     = EventsUri,
                Method  = HttpMethod.Get,
                Timeout = Timeout.Infinite
            });

            task.Wait();

            var response = task.Result;

            if (response?.StatusCode == HttpStatusCode.OK)
            {
                var evt = response?.Data?.FromBytes <Event>();
                if (evt != null)
                {
                    EventsUri = new Uri(evt.Links?.Resync?.Href ?? evt.Links.Next.Href, UriKind.Relative);
                    if (evt.Links?.Resync == null)
                    {
                        OnEventReceived?.Invoke(this, new EventReceivedEventArgs
                        {
                            Resource = evt
                        });
                    }
                }
            }
            else if (response?.StatusCode == HttpStatusCode.Conflict)
            {
                _error = response?.Data?.FromBytes <Error>();
                Stop();
            }
        }
        private async Task Consumer_Received(object sender, BasicDeliverEventArgs eventArgs)
        {
            var eventName = eventArgs.RoutingKey;
            var message   = Encoding.UTF8.GetString(eventArgs.Body);

            var integrationEventReceivedArgs = new IntegrationEventReceivedArgs()
            {
                EventName = eventName,
                Message   = message
            };

            try
            {
                await OnEventReceived?.Invoke(this, integrationEventReceivedArgs);
            }

            catch (Exception ex)
            {
                _logger.LogWarning(ex, "----- ERROR Processing message \"{Message}\"", message);
            }

            // Even on exception we take the message off the queue.
            // in a REAL WORLD app this should be handled with a Dead Letter Exchange (DLX).
            // For more information see: https://www.rabbitmq.com/dlx.html
            _consumerChannel.BasicAck(eventArgs.DeliveryTag, multiple: false);
        }
Exemple #5
0
    public void RemoveListener <T>(OnEventReceived toRemove) where T : EventArgs
    {
        Type type = typeof(T);

        if (Listeners.ContainsKey(type))
        {
            Listeners[type] -= toRemove;
        }
    }
        public void AddEventListener(OnEventReceived onEventReceived)
        {
            //if (lastEventCallback != null) {
            //    PhotonNetwork.OnEventCall -= lastEventCallback;
            //}

            //lastEventCallback = delegate (byte eventCode, object content, int senderId) { onEventReceived(eventCode, content); };
            //PhotonNetwork.OnEventCall += lastEventCallback;
        }
        public void NotifyEventReceived(IntegrationEvent integrationEvent)
        {
            Events.Add(integrationEvent);
            var eventArgs = new EventReceivedNotifierEventArgs()
            {
                Event = integrationEvent
            };

            OnEventReceived?.Invoke(this, eventArgs);
        }
Exemple #8
0
        public void AddEventListener(OnEventReceived i_OnEventReceived)
        {
            if (s_LastEventCallback != null)
            {
                PhotonNetwork.OnEventCall -= s_LastEventCallback;
            }

            s_LastEventCallback        = delegate(byte eventCode, object content, int senderId) { i_OnEventReceived(eventCode, content); };
            PhotonNetwork.OnEventCall += s_LastEventCallback;
        }
        public void AddEventListener(OnEventReceived onEventReceived)
        {
            if (lastEventCallback != null)
            {
                PhotonNetwork.NetworkingClient.EventReceived -= lastEventCallback;
            }

            lastEventCallback = eventData => onEventReceived(eventData.Code, eventData.CustomData);
            PhotonNetwork.NetworkingClient.EventReceived += lastEventCallback;
        }
        public void AddEventListener(OnEventReceived onEventReceived)
        {
            RemoveEventListener();

            // save callback we know how to de-register it
            _lastEventCallback = (Byte eventCode, Object content, Int32 senderId) => onEventReceived(eventCode, content);

            // attach callback
            PhotonNetwork.OnEventCall += _lastEventCallback;
        }
Exemple #11
0
        protected void Event <TEventData>(Expression <Func <Event <TEventData> > > propertyExpression, string fieldName)
        {
            var machineEvent = propertyExpression.Compile().Invoke();

            _messagesToEventsMap[typeof(TEventData)] = machineEvent;
            _acceptedMessageMap.Add(new MessageBind(typeof(TEventData), fieldName));

            base.Event(propertyExpression);

            DuringAny(
                When(machineEvent).Then(
                    ctx =>
                    OnEventReceived.Invoke(this,
                                           new EventReceivedData <TEventData, TSagaData>(ctx.Event, ctx.Data, ctx.Instance))));
        }
Exemple #12
0
    public void AddListener <T>(OnEventReceived toInvoke) where T : EventArgs
    {
        Type type = typeof(T);

        if (!Listeners.ContainsKey(type))
        {
            if (toInvoke != null)
            {
                Listeners.Add(type, toInvoke);
            }
        }
        else
        {
            Listeners[type] += toInvoke;
        }
    }
Exemple #13
0
        private void ClientOnOnMessageReceived(RpcClient rpcClient1, RPCMessage rpcMessage)
        {
            switch (rpcMessage)
            {
            case RPCResponseMessage responseMessage:
                if (!_messageResponsesHandlers.TryRemove(responseMessage.RequestMessageId, out var value))
                {
                    return;
                }
                value.Message = responseMessage;
                value.Event.Set();
                break;

            case RPCEventMessage eventMessage:
                if (!_previousMessages.TryGetValue(eventMessage.MessageId, out _))
                {
                    _previousMessages.TryAdd(eventMessage.MessageId, null);
                    var edea = EventDataEventArgs.Retrieve(eventMessage.ServiceName, eventMessage.EventName, eventMessage.EventArgs);
                    OnEventReceived?.Invoke(this, edea);
                    EventDataEventArgs.Store(edea);
                }
                break;

            case RPCPushMessage pushMessage:
                if (!_previousMessages.TryGetValue(pushMessage.MessageId, out _))
                {
                    _previousMessages.TryAdd(pushMessage.MessageId, null);
                    var evArgs = ReferencePool <EventArgs <RPCPushMessage> > .Shared.New();

                    evArgs.Item1 = pushMessage;
                    OnPushMessageReceived?.Invoke(this, evArgs);
                    evArgs.Item1 = null;
                    ReferencePool <EventArgs <RPCPushMessage> > .Shared.Store(evArgs);
                }
                break;

            case RPCError errorMessage:
                var respMsg = RPCResponseMessage.Retrieve(errorMessage);
                foreach (var mHandler in _messageResponsesHandlers.ToArray())
                {
                    mHandler.Value.Message = respMsg;
                    mHandler.Value.Event.Set();
                    _messageResponsesHandlers.TryRemove(mHandler.Key, out _);
                }
                break;
            }
        }
Exemple #14
0
        public LANClient(ILogger <LANClient> logger)
        {
            var selfAddresses = NetworkInterface.GetAllNetworkInterfaces().SelectMany(ni => ni.GetIPProperties().UnicastAddresses.Select(ua => ua.Address.ToString()));

            _logger = logger;
            try
            {
                receiveUdpClient = new UdpClient(DefaultUdpPort)
                {
                    EnableBroadcast = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogDebug(ex, "Exception");
                throw;
            }
            Task.Run(async() =>
            {
                try
                {
                    while (true)
                    {
                        var receivedResults = await receiveUdpClient.ReceiveAsync();
                        if (selfAddresses.Contains(receivedResults.RemoteEndPoint.Address.ToString()))
                        {
                            //ブロードキャストを自分で受信(無視)
                            continue;
                        }
                        _logger.LogDebug($"UDP受信:{receivedResults.RemoteEndPoint.Address.ToString()} {BytesConvert.ToHexString(receivedResults.Buffer)}");
                        OnEventReceived?.Invoke(this, (receivedResults.RemoteEndPoint.Address.ToString(), receivedResults.Buffer));
                    }
                }
                catch (System.ObjectDisposedException)
                {
                    //握りつぶす
                }
                catch (Exception ex)
                {
                    _logger.LogDebug(ex, "Exception");
                }
            });
        }
        private void ClientOnOnMessageReceived(RpcClient rpcClient1, RPCMessage rpcMessage)
        {
            switch (rpcMessage)
            {
            case RPCResponseMessage responseMessage:
                if (!_messageResponsesHandlers.TryRemove(responseMessage.RequestMessageId, out var value))
                {
                    return;
                }
                value.Message = responseMessage;
                value.Event.Set();
                break;

            case RPCEventMessage eventMessage:
                _previousMessages.GetOrAdd(eventMessage.MessageId, mId =>
                {
                    OnEventReceived?.InvokeAsync(this, new EventDataEventArgs(eventMessage.ServiceName, eventMessage.EventName, eventMessage.EventArgs));
                    return(null);
                });
                break;

            case RPCPushMessage pushMessage:
                _previousMessages.GetOrAdd(pushMessage.MessageId, mId =>
                {
                    OnPushMessageReceived?.InvokeAsync(this, new EventArgs <RPCPushMessage>(pushMessage));
                    return(null);
                });
                break;

            case RPCError errorMessage:
                var respMsg = new RPCResponseMessage {
                    Exception = errorMessage.Exception
                };
                foreach (var mHandler in _messageResponsesHandlers.ToArray())
                {
                    mHandler.Value.Message = respMsg;
                    mHandler.Value.Event.Set();
                    _messageResponsesHandlers.TryRemove(mHandler.Key, out var _);
                }
                break;
            }
        }
 private void RegisterSubscriptionClientMessageHandler()
 {
     _subscriptionClient.RegisterMessageHandler(
         async(message, token) =>
     {
         var eventName   = $"{message.Label}";
         var messageData = Encoding.UTF8.GetString(message.Body);
         var integrationEventReceivedArgs = new IntegrationEventReceivedArgs()
         {
             EventName = eventName,
             Message   = messageData
         };
         await Task.Run(async() => await(OnEventReceived?.Invoke(this, integrationEventReceivedArgs) ?? Task.CompletedTask));
         await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
     },
         new MessageHandlerOptions(ExceptionReceivedHandler)
     {
         MaxConcurrentCalls = 10, AutoComplete = false
     });
 }
Exemple #17
0
 public InMemoryEventSubscriber(BlockingCollection <IntegrationEvent> events)
 {
     _events = events;
     Task.Run(async() =>
     {
         foreach (var integrationEvent in _events.GetConsumingEnumerable())
         {
             string eventName = integrationEvent.GetType().Name;
             if (subscriptions.Contains(eventName))
             {
                 var eventArgs = new IntegrationEventReceivedArgs()
                 {
                     EventName = eventName,
                     Message   = JsonConvert.SerializeObject(integrationEvent)
                 };
                 if (OnEventReceived != null)
                 {
                     await OnEventReceived.Invoke(this, eventArgs);
                 }
             }
         }
     });
 }
Exemple #18
0
        private void Consume(object sender, BasicDeliverEventArgs @event)
        {
            _logger.LogInformation($"received message at {DateTime.UtcNow}, routing key: {@event.RoutingKey}");

            _deliveryTag = @event.DeliveryTag;

            var content = Encoding.UTF8.GetString(@event.Body);

            _logger.LogInformation($"raw content is {content}");

            var baseJsonContent = JsonConvert.DeserializeObject <Dictionary <string, object> >(content);

            var id = GetId(baseJsonContent);

            if (!id.HasValue)
            {
                throw new ArgumentNullException(nameof(id));
            }

            var received = new Received(id.Value, @event.RoutingKey, content, @event.BasicProperties.ReplyTo, @event.BasicProperties.CorrelationId);


            OnEventReceived?.Invoke(sender, received);
        }
Exemple #19
0
 private static void FireEvent(int pid, EventType eventType, int[] args)
 {
     OnEventReceived?.Invoke(pid, eventType, args);
 }
Exemple #20
0
 //
 private static void FireEvent(string pid, GameEvents gameevent, int[] args)
 {
     OnEventReceived?.Invoke(pid, gameevent, args);
 }
Exemple #21
0
 private void Connector_OnEventReceived(object sender, RPCEventArgs e)
 {
     OnEventReceived?.Invoke(this, e);
 }
Exemple #22
0
 /// @param param
 ///     The param received from the event
 ///
 public virtual void TriggerEvent(string param)
 {
     OnEventReceived.SafeInvoke(param);
 }