/// <summary> /// Send a HL7 message /// </summary> /// <param name="message">Message to send</param> /// <returns>Reply message</returns> public string SendHL7Message(string message) { message = MLLP.CreateMLLPMessage(message); // Send the message StreamWriter sw = new StreamWriter(streamToUse); sw.Write(message); sw.Flush(); // Read the reply StringBuilder sb = new StringBuilder(); bool messageComplete = false; while (!messageComplete) { int b = streamToUse.ReadByte(); if (b != -1) { sb.Append((char)b); } messageComplete = MLLP.ValidateMLLPMessage(sb); } MLLP.StripMLLPContainer(sb); return(sb.ToString()); }
public async Task M_EasyCLientSendsCommandToHL7InterfaceWaitAckAndResponse() { HL7InterfaceBase hl7Interface = new HL7InterfaceBase(); AutoResetEvent ackReceived = new AutoResetEvent(false); AutoResetEvent commandResponseReceived = new AutoResetEvent(false); HL7Server serverSide = new HL7Server(); Assert.IsTrue(serverSide.Setup("127.0.0.1", 50060)); Assert.IsTrue(hl7Interface.Initialize(serverSide, new HL7ProtocolBase(new HL7ProtocolConfig()))); Assert.That(hl7Interface.Start()); hl7Interface.NewRequestReceived += (s, e) => { string response = MLLP.CreateMLLPMessage((new PrepareForSpecimenResponse()).Encode()); byte[] dataToSend = Encoding.ASCII.GetBytes(response); s.Send(dataToSend, 0, dataToSend.Length); }; PrepareForSpecimenRequest request = new PrepareForSpecimenRequest(); EasyClient client = new EasyClient(); client.Initialize(new ReceiverFilter(new HL7ProtocolBase()), (packageInfo) => { if (packageInfo.Request.IsAcknowledge) { Assert.That(packageInfo.Request is GeneralAcknowledgment); Assert.That(HL7Parser.IsAckForRequest(request, packageInfo.Request)); ackReceived.Set(); } else { Assert.IsTrue(packageInfo.Request is PrepareForSpecimenResponse); commandResponseReceived.Set(); } }); Assert.That(client.ConnectAsync(endPointA).Result); byte[] bytesToSend = Encoding.ASCII.GetBytes(MLLP.CreateMLLPMessage(request.Encode())); client.Send(bytesToSend); Assert.That(ackReceived.WaitOne()); Assert.That(commandResponseReceived.WaitOne()); await client.Close(); serverSide.Stop(); hl7Interface.Stop(); }
public async Task I_HL7InterfaceSendsMessageToHL7ServerWaitAckAndResponseTest() { HL7InterfaceBase hl7Interface = new HL7InterfaceBase(); HL7Server server = new HL7Server(); AutoResetEvent requestReceived = new AutoResetEvent(false); HL7ProtocolBase protocol = new HL7ProtocolBase(new HL7ProtocolConfig() { IsAckRequired = true, IsResponseRequired = true, AckTimeout = 10000, ResponseTimeout = 50000 }); HL7Server serverSide = new HL7Server(); serverSide.Setup("127.0.0.1", 50060); server.Setup("127.0.0.1", 2012); server.Start(); hl7Interface.Initialize(serverSide, protocol); hl7Interface.Start(); server.NewRequestReceived += (e, s) => { Assert.That(s.Request is PrepareForSpecimenRequest); requestReceived.Set(); Thread.Sleep(500); byte[] bytesToSend = Encoding.ASCII.GetBytes(MLLP.CreateMLLPMessage((new PrepareForSpecimenResponse()).Encode())); e.Send(bytesToSend, 0, bytesToSend.Length); }; bool connected = await hl7Interface.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2012)); Assert.That(connected); HL7Request req = await hl7Interface.SendHL7MessageAsync(new PrepareForSpecimenRequest()); Assert.IsNotNull(req); Assert.That(req.Acknowledgment is GeneralAcknowledgment); Assert.That(req.Acknowledgment.IsAckForRequest(req.Request)); Assert.That(req.Acknowledgment.GetValue("MSA-1") == "AA"); Assert.IsNotNull(req.Response); Assert.That(req.Response.IsResponseForRequest(req.Request)); requestReceived.WaitOne(); server.Stop(); hl7Interface.Stop(); }
static void Send() { string content = @"MSH|^~\&|PEIS||EAI||20190320182547||ZMG^Z30|PEIS_3468011|P|2.4|||AL|AL|CHN PID|1901090088|0000558984|0000558984^^^^IDCard~431002198702161010^^^^IdentifyNO||张洵||19870216|M|||||||||||||||||||||||||||||| PV1|1|T|^^^2400^健康管理中心|||||||||||||0|001921^李东霞|01|1901090088|||||||||0||||||||||||||||20190320182547|||||||0 ORC|NW|T1484237^^1901090088^o|T190109008800095159|1901090088|1||||20190320182547|001921||001921^李东霞|||20190320182547||2400^健康管理中心 OBR|4|||F00000095159^一般健康体检^WZ|||||||||||||||||||45| ZDS||||F00000017022|||||||||||||||||||||||1||||||||||||||||||1|| "; content = MLLP.CreateMLLPMessage(content); var buffer = Encoding.UTF8.GetBytes(content); var temp = socketClient.Send(buffer); Console.WriteLine(temp); Console.WriteLine("发送成功"); }
public async Task SendMessageAsync(string message) { message = MLLP.CreateMLLPMessage(message); var buffer = Encoding.ASCII.GetBytes(message); await _networkStream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false); await _networkStream.FlushAsync().ConfigureAwait(false); var responseBuffer = new byte[4096]; int responseLength = await _networkStream.ReadAsync(responseBuffer, 0, responseBuffer.Length).ConfigureAwait(false); }
public async Task L_EasyClientSendsCommandToHL7InterfaceAndWaitAck() { HL7InterfaceBase hl7Interface = new HL7InterfaceBase(); AutoResetEvent ackReceived = new AutoResetEvent(false); AutoResetEvent commandResponseReceived = new AutoResetEvent(false); HL7ProtocolBase protocol = new HL7ProtocolBase(new HL7ProtocolConfig() { IsAckRequired = true, IsResponseRequired = true }); HL7Server serverSide = new HL7Server(); Assert.IsTrue(serverSide.Setup("127.0.0.1", 50060)); Assert.IsTrue(hl7Interface.Initialize(serverSide, protocol)); Assert.That(hl7Interface.Start()); PrepareForSpecimenRequest request = new PrepareForSpecimenRequest(); EasyClient client = new EasyClient(); client.Initialize(new ReceiverFilter(new HL7ProtocolBase()), (packageInfo) => { if (packageInfo.Request.IsAcknowledge) { Assert.That(packageInfo.Request is GeneralAcknowledgment); Assert.That(HL7Parser.IsAckForRequest(request, packageInfo.Request)); ackReceived.Set(); } else { Assert.Fail(); } }); Assert.That(client.ConnectAsync(endPointA).Result); byte[] bytesToSend = Encoding.ASCII.GetBytes(MLLP.CreateMLLPMessage(request.Encode())); client.Send(bytesToSend); Assert.That(ackReceived.WaitOne(timeout)); await client.Close(); hl7Interface.Stop(); }
private bool SendAndWaitForAck(HL7Request hl7Request, ref int ackRetries) { m_HL7Server.Logger.Info($"Sending {hl7Request.Request.ControlID}"); GlobalWatch.Restart(); m_EasyClient.Send(Encoding.ASCII.GetBytes(MLLP.CreateMLLPMessage(hl7Request.Request.Encode()))); m_HL7Server.Logger.Info($"Sent {hl7Request.Request.ControlID}"); string logMessage = string.Empty; logMessage = $"{hl7Request.Request.MessageID} sent (Ack RETRY) [{m_HL7Protocol.Config.MaxAckRetriesNumber}, {ackRetries}]"; if (!Protocol.Config.IsAckRequired) { return(true); } if (!m_OutgoingRequests.Contains(hl7Request)) { throw new OperationCanceledException(""); } if (hl7Request.RequestCancellationToken.Token.IsCancellationRequested) { throw new OperationCanceledException(hl7Request.RequestCancellationToken.Token); } hl7Request.RequestCancellationToken.Token.ThrowIfCancellationRequested(); m_HL7Server.Logger.Info($"Waiting for ack {hl7Request.Request.ControlID}"); if (!hl7Request.AckReceivedEvent.Wait(Protocol.Config.AckTimeout, hl7Request.RequestCancellationToken.Token)) { m_HL7Server.Logger.Info($"Ack received: {hl7Request.Request.ControlID}"); if (ackRetries-- > 0) { return(false); } else { throw new HL7InterfaceException($"The message was not acknowledged after a total number of {m_HL7Protocol.Config.MaxAckRetriesNumber} retries"); } } return(true); }
public async Task E_EasyClientSendsHL7MessageToHL7InterfaceAndReceivesAck() { HL7InterfaceBase hl7Interface = new HL7InterfaceBase(); AutoResetEvent newRequestReceived = new AutoResetEvent(false); Assert.IsTrue(hl7Interface.Initialize()); Assert.IsTrue(hl7Interface.Start()); PrepareForSpecimenRequest equipmentCommandRequest = new PrepareForSpecimenRequest(); hl7Interface.HL7Server.NewRequestReceived += (hl7Session, hl7Request) => { Assert.That(hl7Request is HL7Request); Assert.IsTrue(hl7Request.Request is PrepareForSpecimenRequest); Assert.That(hl7Session.Connected); }; EasyClient client = new EasyClient(); var tcs = new TaskCompletionSource <IHL7Message>(); client.Initialize(new ReceiverFilter(new HL7ProtocolBase()), (packageInfo) => { tcs.SetResult(packageInfo.Request); }); Assert.That(await client.ConnectAsync(endPointA)); byte[] data = Encoding.ASCII.GetBytes(MLLP.CreateMLLPMessage(equipmentCommandRequest.Encode())); client.Send(data); var result = await tcs.Task; Assert.IsTrue(result.IsAcknowledge); Assert.IsTrue(HL7Parser.IsAckForRequest(equipmentCommandRequest, result)); await client.Close(); hl7Interface.Stop(); }
/// <summary> /// Send a HL7 message /// </summary> /// <param name="message">Message to send</param> /// <returns>Reply message</returns> public string SendHL7Message(string message) { message = MLLP.CreateMLLPMessage(message); // Send the message StreamWriter sw = new StreamWriter(streamToUse); sw.Write(message); sw.Flush(); var stopwatch = new Stopwatch(); if (ReceiveTimeoutInSeconds > 0) { stopwatch.Start(); } // Read the reply StringBuilder sb = new StringBuilder(); bool messageComplete = false; while (!messageComplete) { int b = streamToUse.ReadByte(); if (b != -1) { sb.Append((char)b); } messageComplete = MLLP.ValidateMLLPMessage(sb); if (ReceiveTimeoutInSeconds > 0) { if (stopwatch.ElapsedMilliseconds / 1000 > ReceiveTimeoutInSeconds) { messageComplete = true; stopwatch.Stop(); return(string.Format("Timed out waiting for response after {0} seconds", ReceiveTimeoutInSeconds)); } } } MLLP.StripMLLPContainer(sb); return(sb.ToString()); }
public async Task F_HL7InterfaceReceivesHL7MessageSendsAResponseToEasyClient() { HL7InterfaceBase hl7Interface = new HL7InterfaceBase(); AutoResetEvent newRequestReceived = new AutoResetEvent(false); Assert.IsTrue(hl7Interface.Initialize()); Assert.IsTrue(hl7Interface.Start()); PrepareForSpecimenRequest equipmentCommandRequest = new PrepareForSpecimenRequest(); hl7Interface.HL7Server.NewSessionConnected += (hl7Session) => { Assert.That(hl7Session.Connected); string response = MLLP.CreateMLLPMessage((new PrepareForSpecimenResponse()).Encode()); byte[] dataToSend = Encoding.ASCII.GetBytes(response); hl7Session.Send(dataToSend, 0, dataToSend.Length); }; EasyClient client = new EasyClient(); var tcs = new TaskCompletionSource <IHL7Message>(); client.Initialize(new ReceiverFilter(new HL7ProtocolBase()), (packageInfo) => { tcs.SetResult(packageInfo.Request); }); Assert.That(await client.ConnectAsync(endPointA)); var result = await tcs.Task; Assert.IsTrue(result is PrepareForSpecimenResponse); await client.Close(); hl7Interface.Stop(); }
public async Task J_EasyClientSendsCommandToHL7ServerAndWaitAck() { AutoResetEvent ackReceived = new AutoResetEvent(false); HL7Server hl7Server = new HL7Server(); hl7Server.Setup("127.0.0.1", 50060); hl7Server.Start(); PrepareForSpecimenRequest request = new PrepareForSpecimenRequest(); EasyClient client = new EasyClient(); client.Initialize(new ReceiverFilter(new HL7ProtocolBase()), (packageInfo) => { if (packageInfo.Request.IsAcknowledge) { Assert.That(packageInfo.Request is GeneralAcknowledgment); Assert.That(HL7Parser.IsAckForRequest(request, packageInfo.Request)); ackReceived.Set(); } else { Assert.Fail(); } }); Assert.That(client.ConnectAsync(endPointA).Result); Assert.That(client.IsConnected); byte[] bytesToSend = Encoding.ASCII.GetBytes(MLLP.CreateMLLPMessage(request.Encode())); client.Send(bytesToSend); Assert.That(ackReceived.WaitOne()); await client.Close(); hl7Server.Stop(); }
protected override HL7RequestInfo ProcessMatchedRequest(byte[] readBuffer, int offset, int length) { byte[] msg = new byte[length]; Array.Copy(readBuffer, offset, msg, offset, length); string result = System.Text.UTF8Encoding.UTF8.GetString(msg); // Remove the begin and end marks if (result.Length > 3) { StringBuilder sb = new StringBuilder(result); MLLP.StripMLLPContainer(sb); result = sb.ToString(); } // Remove empty space at the end of the message result = result.TrimEnd(new char[] { ' ', '\r', '\n' }); HL7RequestInfoParser parser = new HL7RequestInfoParser(); return(parser.ParseRequestInfo(result, "MLLP")); }
/// <summary> /// Send a HL7 message /// </summary> /// <param name="message">Message to send</param> /// <param name="timeout">Read timeout, throws exception when receiving no data until timeout</param> /// <returns>Reply message</returns> /// <exception cref="TimeoutException">throws exception on read timeout</exception> public string SendHL7Message(string message, double timeout = 30000) { message = MLLP.CreateMLLPMessage(message); // Send the message StreamWriter sw = new StreamWriter(streamToUse, encodingForStream); sw.Write(message); sw.Flush(); // Read the reply StringBuilder sb = new StringBuilder(); bool messageComplete = false; DateTime startReadingTime = DateTime.Now; while (!messageComplete) { int b = streamToUse.ReadByte(); if (b != -1) { sb.Append((char)b); } messageComplete = MLLP.ValidateMLLPMessage(sb); if (b > 0) // reset start reading time for timout check { startReadingTime = DateTime.Now; } if (!messageComplete && DateTime.Now.Subtract(startReadingTime).TotalMilliseconds > timeout) { throw new TimeoutException($"Reading the HL7 reply timed out after {timeout} milliseconds."); } } MLLP.StripMLLPContainer(sb); return(sb.ToString()); }
/// <summary> /// Send /// </summary> /// <param name="message"></param> public override void Send(string message) { message = MLLP.CreateMLLPMessage(message); base.Send(message); }