private async Task SendResponse( byte[] messageBuilder, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var s = _encoding.GetString(messageBuilder); var received = _parser.Parse(s); var message = new Hl7Message( received, _client.Client.RemoteEndPoint.ToString()); await _messageLog.Write(s).ConfigureAwait(false); var result = await _middleware.Handle(message, cancellationToken) .ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); string resultMsg = _parser.Encode(result); await WriteToStream(resultMsg, cancellationToken) .ConfigureAwait(false); await _messageLog.Write(resultMsg); }
/// <summary> /// Sends the HL7 message to the server. /// </summary> /// <param name="message">The message to send.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the async operation.</param> /// <returns></returns> public async Task <Hl7Message> Send <TMessage>( TMessage message, CancellationToken cancellationToken = default) where TMessage : IMessage { await _semaphore.WaitAsync(cancellationToken); var hl7 = _parser.Encode(message); var bytes = _encoding.GetBytes(hl7); var length = bytes.Length + Constants.StartBlock.Length + Constants.EndBlock.Length; var buffer = ArrayPool <byte> .Shared.Rent(length); Array.Copy( Constants.StartBlock, 0, buffer, 0, Constants.StartBlock.Length); Array.Copy( bytes, 0, buffer, Constants.StartBlock.Length, bytes.Length); Array.Copy( Constants.EndBlock, 0, buffer, Constants.StartBlock.Length + bytes.Length, Constants.EndBlock.Length); var completionSource = new TaskCompletionSource <Hl7Message>(); var key = message.GetMessageControlId(); _messages.Add(key, completionSource); await _messageLog.Write(hl7).ConfigureAwait(false); await _stream.WriteAsync(buffer, 0, length, cancellationToken) .ConfigureAwait(false); ArrayPool <byte> .Shared.Return(buffer); _semaphore.Release(1); return(await completionSource.Task.ConfigureAwait(false)); }