dib0 / NHapiTools

The NHapiTools are tools that will make using NHapi (the open source .Net HL7 implementation) easier. NHapi has a steep learning curve and not everything works as easy as it should. NHapiTools aims to improve that without tampering with NHapi itselves.
MIT License
85 stars 59 forks source link

SendHL7Message may never return #20

Closed alaa9jo closed 3 years ago

alaa9jo commented 3 years ago

Case: Let's say the destination service may not reply with any bytes if the message you send has incorrect values set in segments; it simply ignore the message you send and ReadByte() return -1

This is a snippet code of function SendHL7Message:

StringBuilder sb = new StringBuilder();
bool messageComplete = false;
while (!messageComplete) {
  int b = streamToUse.ReadByte();
  if (b != -1)
    sb.Append((char) b);

  messageComplete = MLLP.ValidateMLLPMessage(sb);
}

streamToUse.ReadByte() will always return -1 in that case, and function MLLP.ValidateMLLPMessage will always return false since sb.length is not > 3, look at below code:

public static bool ValidateMLLPMessage(StringBuilder sb) {
  bool result = false;

  if (sb.Length > 3) {
    if (((int) sb[0] == MLLP_START_CHARACTER)) {
      if (((int) sb[sb.Length - 2] == MLLP_FIRST_END_CHARACTER) && ((int) sb[sb.Length - 1] == MLLP_LAST_END_CHARACTER))
        result = true;
    }
  }

  return result;
}

What happens is that the code will get stuck in infinite loop, SendHL7Message will never return and the caller will get stuck.

There should be a way to break from this loop, maybe return a custom timeout error if streamToUse.ReadByte() repeatedly returns 0 bytes for some time?

dib0 commented 3 years ago

Thanks! I've added an optional timeout parameter. It will throw a TimeoutException on timeout. This will be included in the next release