/// <summary> /// Message received /// </summary> /// <param name="message"></param> protected void OnMessageReceived(Hl7MessageReceivedEventArgs messageArgs) { if (this.MessageReceived != null) { this.MessageReceived(this, messageArgs); } }
/// <summary> /// Receive and process message /// </summary> private void ReceiveMessage(object client) { TcpClient tcpClient = client as TcpClient; NetworkStream stream = tcpClient.GetStream(); try { // Now read to a string NHapi.Base.Parser.PipeParser parser = new NHapi.Base.Parser.PipeParser(); StringBuilder messageData = new StringBuilder(); byte[] buffer = new byte[1024]; while (stream.DataAvailable) { int br = stream.Read(buffer, 0, 1024); messageData.Append(Encoding.ASCII.GetString(buffer, 0, br)); } var message = parser.Parse(messageData.ToString()); var localEp = tcpClient.Client.LocalEndPoint as IPEndPoint; var remoteEp = tcpClient.Client.RemoteEndPoint as IPEndPoint; Uri localEndpoint = new Uri(String.Format("tcp://{0}:{1}", localEp.Address, localEp.Port)); Uri remoteEndpoint = new Uri(String.Format("tcp://{0}:{1}", remoteEp.Address, remoteEp.Port)); var messageArgs = new Hl7MessageReceivedEventArgs(message, localEndpoint, remoteEndpoint, DateTime.Now); this.MessageReceived(this, messageArgs); // Send the response back StreamWriter writer = new StreamWriter(stream); if (messageArgs.Response != null) { writer.Write(parser.Encode(messageArgs.Response)); writer.Flush(); } } catch (Exception e) { Trace.TraceError(e.ToString()); // TODO: NACK } finally { stream.Close(); } }
/// <summary> /// Receive and process message /// </summary> protected virtual void OnReceiveMessage(object client) { TcpClient tcpClient = client as TcpClient; NetworkStream stream = tcpClient.GetStream(); try { // Now read to a string NHapi.Base.Parser.PipeParser parser = new NHapi.Base.Parser.PipeParser(); DateTime lastReceive = DateTime.Now; while (DateTime.Now.Subtract(lastReceive) < this.m_timeout) { if (!stream.DataAvailable) { Thread.Sleep(10); continue; } // Read LLP head byte int llpByte = stream.ReadByte(); if (llpByte != START_TX) // first byte must be HT { throw new InvalidOperationException("Invalid LLP First Byte"); } // Standard stream stuff, read until the stream is exhausted StringBuilder messageData = new StringBuilder(); byte[] buffer = new byte[1024]; bool receivedEOF = false, scanForCr = false; while (!receivedEOF) { if (DateTime.Now.Subtract(lastReceive) > this.m_timeout) { throw new TimeoutException("Data not received in the specified amount of time. Increase the timeout or check the network connection"); } if (!stream.DataAvailable) { Thread.Sleep(10); continue; } int br = stream.Read(buffer, 0, 1024); messageData.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, br)); // Need to check for CR? if (scanForCr) { receivedEOF = buffer[0] == END_TXNL; } else { // Look for FS int fsPos = Array.IndexOf(buffer, (byte)END_TX); if (fsPos == -1) // not found { continue; } else if (fsPos < buffer.Length - 1) // more room to read { receivedEOF = buffer[fsPos + 1] == END_TXNL; } else { scanForCr = true; // Cannot check the end of message for CR because there is no more room in the message buffer } // so need to check on the next loop } } // Use the nHAPI parser to process the data Hl7MessageReceivedEventArgs messageArgs = null; try { // Setup local and remote receive endpoint data for auditing var localEp = tcpClient.Client.LocalEndPoint as IPEndPoint; var remoteEp = tcpClient.Client.RemoteEndPoint as IPEndPoint; Uri localEndpoint = new Uri(String.Format("llp://{0}:{1}", localEp.Address, localEp.Port)); Uri remoteEndpoint = new Uri(String.Format("llp://{0}:{1}", remoteEp.Address, remoteEp.Port)); #if DEBUG Trace.TraceInformation("Received message from llp://{0}:{1} : {2}", remoteEp.Address, remoteEp.Port, messageData); #endif // HACK: nHAPI doesn't like URLs ... Will fix this later string messageString = messageData.ToString().Replace("|URL|", "|ST|"); var message = parser.Parse(messageString); messageArgs = new Hl7MessageReceivedEventArgs(message, localEndpoint, remoteEndpoint, DateTime.Now); // Call any bound event handlers that there is a message available OnMessageReceived(messageArgs); } finally { // Send the response back using (MemoryStream memoryWriter = new MemoryStream()) { using (StreamWriter streamWriter = new StreamWriter(memoryWriter)) { memoryWriter.Write(new byte[] { START_TX }, 0, 1); // header if (messageArgs != null && messageArgs.Response != null) { var strMessage = parser.Encode(messageArgs.Response); #if DEBUG Trace.TraceInformation("Sending message to llp://{0} : {1}", tcpClient.Client.RemoteEndPoint, strMessage); #endif // Since nHAPI only emits a string we just send that along the stream streamWriter.Write(strMessage); streamWriter.Flush(); } memoryWriter.Write(new byte[] { END_TX, END_TXNL }, 0, 2); // Finish the stream with FSCR stream.Write(memoryWriter.ToArray(), 0, (int)memoryWriter.Position); stream.Flush(); } } lastReceive = DateTime.Now; // Update the last receive time so the timeout function works } } } catch (Exception e) { Trace.TraceError(e.ToString()); } finally { stream.Close(); tcpClient.Close(); } }
/// <summary> /// Receive a message /// </summary> protected override void OnReceiveMessage(object client) { TcpClient tcpClient = client as TcpClient; SslStream stream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(RemoteCertificateValidation)); try { // Setup local and remote receive endpoint data for auditing var localEp = tcpClient.Client.LocalEndPoint as IPEndPoint; var remoteEp = tcpClient.Client.RemoteEndPoint as IPEndPoint; Uri localEndpoint = new Uri(String.Format("sllp://{0}:{1}", localEp.Address, localEp.Port)); Uri remoteEndpoint = new Uri(String.Format("sllp://{0}:{1}", remoteEp.Address, remoteEp.Port)); Trace.TraceInformation("Accepted TCP connection from {0} > {1}", remoteEndpoint, localEndpoint); stream.AuthenticateAsServer(this.m_configuration.ServerCertificate, this.m_configuration.EnableClientCertNegotiation, System.Security.Authentication.SslProtocols.Tls, this.m_configuration.CheckCrl); // Now read to a string NHapi.Base.Parser.PipeParser parser = new NHapi.Base.Parser.PipeParser(); DateTime lastReceive = DateTime.Now; while (DateTime.Now.Subtract(lastReceive) < this.m_timeout) { int llpByte = 0; // Read LLP head byte try { llpByte = stream.ReadByte(); } catch (SocketException) { break; } if (llpByte != START_TX) // first byte must be HT { Trace.TraceWarning("Invalid LLP First Byte expected 0x{0:x} got 0x{1:x} from {2}", START_TX, llpByte, remoteEndpoint); break; } // throw new InvalidOperationException("Invalid LLP First Byte"); // Standard stream stuff, read until the stream is exhausted StringBuilder messageData = new StringBuilder(); byte[] buffer = new byte[1024]; bool receivedEOF = false, scanForCr = false; while (!receivedEOF) { int br = stream.Read(buffer, 0, 1024); messageData.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, br)); // Need to check for CR? if (scanForCr) { receivedEOF = buffer[0] == END_TXNL; } else { // Look for FS int fsPos = Array.IndexOf(buffer, END_TX); if (fsPos == -1) // not found { continue; } else if (fsPos < buffer.Length - 1) // more room to read { receivedEOF = buffer[fsPos + 1] == END_TXNL; } else { scanForCr = true; // Cannot check the end of message for CR because there is no more room in the message buffer } // so need to check on the next loop } // TODO: Timeout for this } // Use the nHAPI parser to process the data Hl7MessageReceivedEventArgs messageArgs = null; try { var message = parser.Parse(messageData.ToString()); #if DEBUG Trace.TraceInformation("Received message from sllp://{0} : {1}", tcpClient.Client.RemoteEndPoint, messageData.ToString()); #endif messageArgs = new AuthenticatedHl7MessageReceivedEventArgs(message, localEndpoint, remoteEndpoint, DateTime.Now, stream.RemoteCertificate.GetPublicKey()); // Call any bound event handlers that there is a message available OnMessageReceived(messageArgs); } finally { // Send the response back using (MemoryStream memoryWriter = new MemoryStream()) { using (StreamWriter streamWriter = new StreamWriter(memoryWriter)) { memoryWriter.Write(new byte[] { START_TX }, 0, 1); // header if (messageArgs != null && messageArgs.Response != null) { var strMessage = parser.Encode(messageArgs.Response); #if DEBUG Trace.TraceInformation("Sending message to sllp://{0} : {1}", tcpClient.Client.RemoteEndPoint, strMessage); #endif // Since nHAPI only emits a string we just send that along the stream streamWriter.Write(strMessage); streamWriter.Flush(); } memoryWriter.Write(new byte[] { END_TX, END_TXNL }, 0, 2); // Finish the stream with FSCR stream.Write(memoryWriter.ToArray(), 0, (int)memoryWriter.Position); stream.Flush(); } } lastReceive = DateTime.Now; // Update the last receive time so the timeout function works } } } catch (AuthenticationException e) { // Trace authentication error AuditData ad = new AuditData( DateTime.Now, ActionType.Execute, OutcomeIndicator.MinorFail, EventIdentifierType.ApplicationActivity, new AuditCode("110113", "DCM") { DisplayName = "Security Alert" } ); ad.Actors = new List <AuditActorData>() { new AuditActorData() { NetworkAccessPointId = Dns.GetHostName(), NetworkAccessPointType = NetworkAccessPointType.MachineName, UserName = Environment.UserName, UserIsRequestor = false }, new AuditActorData() { NetworkAccessPointId = String.Format("sllp://{0}", tcpClient.Client.RemoteEndPoint.ToString()), NetworkAccessPointType = NetworkAccessPointType.MachineName, UserIsRequestor = true } }; ad.AuditableObjects = new List <AuditableObject>() { new AuditableObject() { Type = AuditableObjectType.SystemObject, Role = AuditableObjectRole.SecurityResource, IDTypeCode = AuditableObjectIdType.Uri, ObjectId = String.Format("sllp://{0}", this.m_listener.LocalEndpoint) } }; var auditService = ApplicationContext.Current.GetService(typeof(IAuditorService)) as IAuditorService; if (auditService != null) { auditService.SendAudit(ad); } Trace.TraceError(e.ToString()); } catch (Exception e) { Trace.TraceError(e.ToString()); // TODO: NACK } finally { stream.Close(); tcpClient.Close(); } }