/// <summary> /// Sends a message via HTTP. /// </summary> /// <param name="action"></param> /// <param name="request"></param> /// <returns></returns> public virtual Response SendMessage(string action, ServerRequest request) { // Initialise the connection and send the message try { InitialiseRemoting(); FireRequestSending(action, request); Response result = client.ProcessMessage(action, request); FireResponseReceived(action, result); return(result); } catch (Exception error) { // Replace the original exception with a communications exception throw new CommunicationsException(error.Message); } }
public async Task InvokeAsync(HttpContext context) { if (!context.WebSockets.IsWebSocketRequest) { await _next.Invoke(context); return; } var requestToken = context.RequestAborted; var currentSocket = await context.WebSockets.AcceptWebSocketAsync(); var userId = Guid.NewGuid().ToString(); while (currentSocket.State == WebSocketState.Open && !requestToken.IsCancellationRequested) { try { var rawMessage = await _webSocketsService.ExtractMessage(currentSocket, requestToken); if (!string.IsNullOrEmpty(rawMessage)) { var extractedMessage = _messageService.DeserializeMessage(rawMessage); extractedMessage.User.WebSocket = currentSocket; if (string.IsNullOrEmpty(extractedMessage.User.Id)) { extractedMessage.User.Id = userId; } _messageProcessor.ProcessMessage(extractedMessage); } } catch (WebSocketException ex) { _messageProcessor.ProcessMessage(new ErrorMessage(ex.Message)); } catch (Exception ex) { _messageProcessor.ProcessMessage(new ErrorMessage(ex.Message)); } } await currentSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", requestToken); }
public void Run() { string input; _consoleUI.OutputStartup(Messages.Startup); while (true) { if (GlobalConfig.AppRestart == false) { input = _consoleUI.GetInput(Messages.GetHours); if (_mp.ProcessMessage(input) == CommandType.Value) { // Process time. input.ConvertHoursToSeconds().SumSeconds(); } } if (GlobalConfig.AppRestart == false) { input = _consoleUI.GetInput(Messages.GetMinuites); if (_mp.ProcessMessage(input) == CommandType.Value) { // Process time. input.ConvertMinuitesToSeconds().SumSeconds(); } } if (GlobalConfig.AppRestart == false) { input = _consoleUI.GetInput(Messages.GetSeconds); if (_mp.ProcessMessage(input) == CommandType.Value) { // process time. input.ConvertSecondsToSeconds().SumSeconds(); } } if (GlobalConfig.AppRestart == false) { _consoleUI.OutputResult(Messages.ResultMessage, TimeConverter.TotalSeconds.ToString()); ClipboardService.SetText(TimeConverter.TotalSeconds.ToString()); TimeConverter.TotalSeconds = 0; } GlobalConfig.AppRestart = false; } }
public async Task ProcessMessage(IncomingMessage message) { PlayerInfo playerInfo = await _playersState.GetById(message.PlayerId); T playerData = await _playersData.GetById(message.PlayerId); await _messageProcessor.ProcessMessage(message, playerInfo, playerData); await _playersData.Update(playerData); }
private void ProcessMessage(byte[] msg) { try { _processor.ProcessMessage(msg); } catch (Exception ex) { LogHelper.LogError(ex); } }
public MessageResult ProcessMessage(Message message) { try { return(m_Underlying.ProcessMessage(message)); } catch (Exception e) { LogException(e); return(MessageResult.Empty); } }
protected void OnMessageReceived(IProcessor processor, string queue, BasicDeliverEventArgs args) { var message = _builder.BuildMessage(queue, 1, Encoding.UTF8.GetString(args.Body)); try { SetReplyQueue(args, message); _messageProcessor.ProcessMessage(message, _publisher, processor.ProcessMessage); _channel.BasicAck(args.DeliveryTag, false); } catch (Exception ex) { ProccessException(processor, args, message, ex); } }
/// <summary> /// Multithreaded message processor for different trade types. Other options can be discussed. /// </summary> /// <param name="messageQueue"></param> /// <param name="processor"></param> private void ProcessMessage(ConcurrentQueue <TradeMessage> messageQueue, IMessageProcessor processor) { // Retry for multiple times. Then throw a fatal error and block the channel. There can be different versions to continue but tell downstream system // to indicate pending erroneous trades. // Not implementing the Exception handling, retry and persistence due to time constraint. while (true) { if (messageQueue.TryDequeue(out TradeMessage msg)) { logger.Info($"Processing sequence number: {msg.Header.SequenceNumber} and TradeID: {msg.Trade.TradeID} " + $"on Thread ID: {Thread.CurrentThread.ManagedThreadId}"); processor.ProcessMessage(msg); } } }
private void NetworkClientMessageReceived(object sender, NetworkClientMessageReceivedEventArgs e) { if (ClientMessageReceived != null) { var messageText = Encoding.UTF8.GetString(e.Message).TrimEnd(); var clientMessage = _messageProcessor.ProcessMessage(messageText); _logger.LogFormat("CLIENT: {0}", messageText); if (messageText.Length > 0 && ClientMessageReceived != null) { ClientMessageReceived(sender, new ClientMessageReceivedEventArgs(e.Client, e.CancellationToken, clientMessage)); } } }
//called from window system each frame, updates all components public void Update(double dt) { if (state != GameMasterState.Configuration && NetworkComponent?.Exception != null) { SetCriticalException(NetworkComponent.Exception); } if (state == GameMasterState.Configuration || state == GameMasterState.Summary || state == GameMasterState.CriticalError) { return; } foreach (var agent in Agents) { agent.Update(dt); } var messages = GetIncomingMessages(); if (messages.Count > 0) { Logger.Get().Debug("[GM] Processing {n} message(s)", messages.Count); NLog.NestedDiagnosticsContext.Push(" "); foreach (var message in messages) { var response = currentMessageProcessor.ProcessMessage(message); response.SetCorrelationId(message.CorrelationId); SendMessage(response); } NLog.NestedDiagnosticsContext.Pop(); } var result = ScoreComponent.GetGameResult(); if (result != Enums.GameResult.None) { state = GameMasterState.Summary; Logger.Get().Info("[GM] Ending game"); var resultMessages = GameLogic.GetEndGameMessages(result == Enums.GameResult.BlueWin ? TeamId.Blue : TeamId.Red); foreach (var m in resultMessages) { SendMessage(m); } } }
public IHttpActionResult ProcessMessage(string inputMessage) { try { var isValidMessage = messageProcessor.ValidateMessage(inputMessage); if (!isValidMessage) { return(BadRequest("Invalid input message")); } else { var objProcessed = messageProcessor.ProcessMessage(inputMessage); return(Ok(objProcessed)); } } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public void Consume(string queueName) { var factory = new RabbitMQConnection( new RabbitMQConnectionDetail() { HostName = "localhost", UserName = "******", Password = "******" } ); using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { var rabbitMQHelper = new RabbitMQHelper(channel, ""); var readMsg = rabbitMQHelper.ReadMessageFromQueue(queueName); string resultString = System.Text.Encoding.UTF8.GetString(readMsg, 0, readMsg.Length); _messageProcessor.ProcessMessage(resultString); } }
protected virtual void HandleMessage(string physicalChannel, RedisValue rawMessage, IMessageProcessor processor) { try { if (!_messageParser.TryParse(rawMessage, out var parsedMessage)) { OnInvalidMessageFormat(physicalChannel, rawMessage); return; } processor.ProcessMessage(parsedMessage, physicalChannel); } catch (Exception exception) { var shouldRethrowException = OnMessageHandlingException(exception); if (shouldRethrowException) { throw; } } }
/// <summary> /// Calls <see cref="IMessageProcessor.ProcessMessage"/> for each flushed message in this /// <see cref="ChannelOutboundBuffer"/> until <see cref="IMessageProcessor.ProcessMessage"/> returns /// <c>false</c> or there are no more flushed messages to process. /// </summary> /// <param name="processor"> /// The <see cref="IMessageProcessor"/> intance to use to process each flushed message. /// </param> public void ForEachFlushedMessage(IMessageProcessor processor) { Contract.Requires(processor != null); Entry entry = this.flushedEntry; if (entry == null) { return; } do { if (!entry.Cancelled) { if (!processor.ProcessMessage(entry.Message)) { return; } } entry = entry.Next; }while (this.IsFlushedEntry(entry)); }
public void Consume(CancellationToken token, string queueName) { _consumerTask = Task.Run(() => { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: queueName, durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); _messageProcessor.ProcessMessage(message); }; channel.BasicConsume(queue: queueName, autoAck: false, consumer: consumer); while (!token.IsCancellationRequested) { Thread.Sleep(1000); } } } }); }
public MessageContext OpenEnvelope(Envelope envelope) { // create a context for processing MessageContext ctx = new MessageContext(MessageContext.Directions.In, envelope); // a marker that indicates the processing result bool isOpen = false; try { _messageProcessor.ProcessMessage(ctx, () => { isOpen = true; }); } catch (Exception ex) { const string msg = "Failed to open an envelope."; Log.Error(msg, ex); throw new MessageException(msg, ex); } // if we successfully opened the envelope, return(isOpen ? ctx : null); }
public void ProcessMessage( MessageContext context, List <IMessageProcessor> processingChain, Action continueProcessing) { // if the chain is null or empty, complete processing if ((null == processingChain) || (!processingChain.Any())) { Log.Debug(string.Format("Message processing complete. Direction: {0}", context.Direction)); continueProcessing(); return; } // get the first processor IMessageProcessor processor = processingChain.First(); // create a processing chain that no longer contains this processor List <IMessageProcessor> newChain = processingChain.Skip(1).ToList(); // let it process the message and pass its "next" processor: a method that // recursively calls this function with the current processor removed Log.Debug(string.Format("Handing message to processor: {0} - Direction: {1}", processor.GetType(), context.Direction)); processor.ProcessMessage(context, () => ProcessMessage(context, newChain, continueProcessing)); }
protected override object HandleRequestMessage(IMessage message) { return(_processor.ProcessMessage(message)); }
private void CommunicatorOnDataReceived(object sender, string s) { _messageProcessor.ProcessMessage(s, RobotState, Controllers); }
public static MessageResult ProcessMessage(this IMessageProcessor processor) { return(processor.ProcessMessage(new Message("channel", "user", "message"))); }
public RedisChannelConsumer(AbstractConsumerSettings consumerSettings, ISubscriber subscriber, IMessageProcessor <byte[]> messageProcessor) { _channelMessageQueue = subscriber.Subscribe(consumerSettings.Topic); _channelMessageQueue.OnMessage(m => messageProcessor.ProcessMessage(m.Message)); }
public async Task ProcessMessages() { await Task.WhenAll(ReceivedMessages.Select(m => _messageProcessor.ProcessMessage(m, _messageReceiver)).ToArray()).ConfigureAwait(false); }
/// <summary> /// Starts the loop for polling the SQS queue /// </summary> public async void Run() { Log.InfoFormat("[{0}] Starting message pump", Id); while (!_cancellationToken.IsCancellationRequested) { Log.TraceFormat("[{0}] Starting receiving call", Id); try { IEnumerable <TransportMessage> recievedMessages = await _queue.GetMessages(_cancellationToken.Token); Log.TraceFormat("[{1}] Received {0} messages", recievedMessages.Count(), Id); foreach (TransportMessage message in recievedMessages) { Log.InfoFormat("[{1}] Received message of type '{0}'", message.MessageTypeName, Id); _messageLogger.InboundLogMessage(message.Body, message.MessageTypeName, message.Id, message.AttemptNumber); MessageProcessingResult result; if (message.MessageParsingSucceeded) { Log.TraceFormat("[{0}] Processing message", Id); result = _messageProcessor.ProcessMessage(message, _bus); Log.TraceFormat("[{0}] Processed message - Error: {1}", Id, !result.WasSuccessful); } else { Log.ErrorFormat("[{1}] Failed to parse message of type {0}", message.Exception, message.MessageTypeName, Id); result = new MessageProcessingResult() { WasSuccessful = false, Exception = new Exception("Message parse failure") }; } if (result.WasSuccessful) { Log.InfoFormat("[{0}] Removing message from the queue", Id); _queue.RemoveMessage(message); } else if (message.AttemptNumber == _messageRetryCount) { Log.InfoFormat("[{0}] Message faulted ", Id); _messageProcessor.ProcessFaultedMessage(message, _bus, result.Exception); } MessageStatistics stats = new MessageStatistics() { FinalAttempt = message.AttemptNumber == _messageRetryCount, HandlerRunTime = result.Runtime, MessageLength = message.Body.Length, MessageType = message.MessageTypeName, Success = result.WasSuccessful, PreviousRetryCount = message.AttemptNumber, }; _messageProcessor.ProcessMessageStatistics(stats); } } catch (OperationCanceledException) { } catch (Exception ex) { Log.ErrorFormat("[{0}] Error occurred in message pump run", ex, Id); } } }
async Task ListenForMessages() { this.messageLoopSyncContext = SynchronizationContext.Current; // Ensure that the console is using UTF-8 encoding System.Console.InputEncoding = Encoding.UTF8; System.Console.OutputEncoding = Encoding.UTF8; // Open the standard input/output streams this.inputStream = System.Console.OpenStandardInput(); this.outputStream = System.Console.OpenStandardOutput(); IMessageSerializer messageSerializer = null; IMessageProcessor messageProcessor = null; // Use a different serializer and message processor based // on whether this instance should host a language server // debug adapter. if (this.runDebugAdapter) { DebugAdapter debugAdapter = new DebugAdapter(); debugAdapter.Initialize(); messageProcessor = debugAdapter; messageSerializer = new V8MessageSerializer(); } else { // Set up the LanguageServer LanguageServer languageServer = new LanguageServer(); languageServer.Initialize(); messageProcessor = languageServer; messageSerializer = new JsonRpcMessageSerializer(); } // Set up the reader and writer this.messageReader = new MessageReader( this.inputStream, messageSerializer); this.messageWriter = new MessageWriter( this.outputStream, messageSerializer); // Set up the console host which will send events // through the MessageWriter this.consoleHost = new StdioConsoleHost(messageWriter); // Set up the PowerShell session this.editorSession = new EditorSession(); this.editorSession.StartSession(this.consoleHost); this.editorSession.PowerShellContext.OutputWritten += powerShellContext_OutputWritten; if (this.runDebugAdapter) { // Attach to debugger events from the PowerShell session this.editorSession.DebugService.DebuggerStopped += DebugService_DebuggerStopped; } // Run the message loop bool isRunning = true; while (isRunning) { Message newMessage = null; try { // Read a message from stdin newMessage = await this.messageReader.ReadMessage(); } catch (MessageParseException e) { // TODO: Write an error response Logger.Write( LogLevel.Error, "Could not parse a message that was received:\r\n\r\n" + e.ToString()); // Continue the loop continue; } // Process the message await messageProcessor.ProcessMessage( newMessage, this.editorSession, this.messageWriter); } }
private void ProcessMessages(IList<RoomMessage> messages, IMessageProcessor processor) { foreach (var message in messages) { if (processor.IsRegisteredMessageType(message.MessageType)) { processor.ProcessMessage(message, new RepsonseClient(_roomId, _proxy)); } } }
public MessageResult Message(Message message) { return(m_Processor.ProcessMessage(message)); }
private void ProcessData() { if (port == null || messageProcessor == null) { throw new InvalidOperationException(); } var data = ReadData(0, false); if (data.Length > 0) { logger.DebugFormat("RX: {0}", Utilities.ByteArrayToString(data)); } lock (buffer) { if (data.Length > 0) { buffer.AddRange(data); } data = buffer.ToArray(); buffer.Clear(); } if (data.Length > 0) { int count = 0; int offset = 0; int last = 0; while (offset < data.Length) { if (data[offset++] == Constants.MessageStartByte) { if (last != offset - 1) { logger.WarnFormat("Skipping {0} bytes to '{1}', discarded '{2}'", offset - last, Utilities.ByteArrayToString(data, offset - 1), Utilities.ByteArrayToString(data, 0, offset - 1)); } // loop until message successfully processed or until there is no more data available on the serial port... while (true) { if (messageProcessor.ProcessMessage(data, offset, out count)) { offset += count; last = offset; break; // break out of the loop when message successfully processed } var appendData = ReadData(1, false); // try to read at least one more byte, waits up to Constants.readTime milliseconds if (appendData.Length == 0) { logger.WarnFormat("Could not process data '{0}'", Utilities.ByteArrayToString(data)); break; // break out of the loop when there is no more data available on the serial port } var list = new List <byte>(data); list.AddRange(appendData); data = list.ToArray(); logger.DebugFormat("RX: {0} (appended)", Utilities.ByteArrayToString(data)); } } } if (last != offset) { logger.WarnFormat("Discarding {0} bytes '{1}'", offset - last, Utilities.ByteArrayToString(data, last)); } } }
public void ProcessMessage( MessageContext context, Action onComplete) { _messageProcessor.ProcessMessage(context, onComplete); }