private void HL7ClientProc(object state)
{
Socket socket = (Socket)state;
try {
Interlocked.Increment(ref _clients);
Debug.Log.Info("HL7 client connected: " + socket.RemoteEndPoint);
NetworkStream stream = new NetworkStream(socket);
MLLP mllp = new MLLP(stream, false, _encoding);
while (socket.Connected && !_stop)
{
if (!socket.Poll(100000, SelectMode.SelectRead))
{
continue;
}
try {
if (!stream.DataAvailable)
{
break;
}
} catch {
// http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.dataavailable.aspx
// "If the remote host shuts down or closes the connection, DataAvailable may throw a SocketException."
break;
}
string hl7 = mllp.Receive();
if (OnReceiveMessage != null)
{
try {
HL7v2 req = HL7v2.Parse(hl7);
HL7v2 rsp = OnReceiveMessage(mllp, req, socket);
if (rsp != null)
{
mllp.Send(rsp.ToString());
}
} catch (Exception ex) {
Debug.Log.Error("Error processing HL7 message: " + ex.ToString());
}
}
}
Debug.Log.Info("HL7 client closed: " + socket.RemoteEndPoint);
try {
socket.Close();
} catch {
}
} catch {
Debug.Log.Info("HL7 client closed on error");
} finally {
Interlocked.Decrement(ref _clients);
}
}