Vous êtes sur la page 1sur 2

Using C# To Send A HL7 Message For one of my current projects I needed to take a HL7 message and send it to our

interface server. Generally there are two ways that HL7 messages are sent, they are either dumped out as a file to a directory, or they are sent over a TCP connection. For this project I needed to send it over a TCP connection. Most HL7 connections that are using TCP will use a the Lower Layer Protocol (LLP). It turns out this is pretty easy to do in C#. First we need to understand what we need to do to send the message using LLP. All that is required is to insert a vertical tab at the start of the message, and a field separator character and carriage return at the end of the message. Here is the function that I created that will send a HL7 message. Sending the message is just that same as sending anything else over a TCP/IP connection. There are a ton of examples of how to do that, so I will not go over it. Once you get the response back you need to check it so see if the message was processed successfully or not. My requirements where pretty simple, so I just checked to make sure it had MSA|AA in the return message, signify that it was successful. Here is the function that I created to send the HL7 message. It has a helper function to connect the socket. private static bool SendHL7(string server, int port, string hl7message) { try { // Add the leading and trailing characters so it is LLP complaint. string llphl7message = Convert.ToChar(11).ToString() + hl7message + Convert.ToChar(28).ToString() + Convert.ToChar(13).ToString(); // Get the size of the message that we have to send. Byte[] bytesSent = Encoding.ASCII.GetBytes(llphl7message); Byte[] bytesReceived = new Byte[256]; // Create a socket connection with the specified server and port. Socket s = ConnectSocket(server, port); // If the socket could not get a connection, then return false. if (s == null) return false; // Send message to the server. s.Send(bytesSent, bytesSent.Length, 0); // Receive the response back int bytes = 0; s.ReceiveTimeout = 3000; bytes = s.Receive(bytesReceived, bytesReceived.Length, 0); string page = Encoding.ASCII.GetString(bytesReceived, 0, bytes); s.Close(); // Check to see if it was successful if (page.Contains("MSA|AA")) { return true; } else { return false;

} } catch (Exception) { return false; } } private static Socket ConnectSocket(string server, int port) { Socket s = null; IPHostEntry hostEntry = null; // Get host related information. hostEntry = Dns.GetHostEntry(server); foreach (IPAddress address in hostEntry.AddressList) { IPEndPoint ipe = new IPEndPoint(address, port); Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tempSocket.Connect(ipe); if (tempSocket.Connected) { s = tempSocket; break; } else { continue; } } return s; }