3

I am trying to create HL7 listener in python. I am able to receive the messages through socket , but not able to send valid acknowledgement

ack=u"\x0b MSH|^~\\&|HL7Listener|HL7Listener|SOMEAPP|SOMEAPP|20198151353||ACK^A08||T|2.3\x1c\x0d MSA|AA|153681279959711 \x1c\x0d"
ack = "MSH|^~\&|HL7Listener|HL7Listener|SOMEAPP|SOMEAPP|20198151353||ACK^A08||T|2.3 \r MSA|AA|678888295637322 \r"
ack= bytes(ack,'utf-8')

Python code :

def listner_hl7():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.bind((socket.gethostname(), 4444))
    except Exception as e:
        print(str(e))
    s.listen(5)
    while True:
        clientSocket, addr = s.accept()
        message = clientSocket.recv(2048)
        id = (str(message.splitlines()[0]).split('|')[9])

        print('received {} bytes from {}'.format(
            len(message), addr))

        print('sending acknowledgement: ')
        ack = b"\x0b MSH|^~\\&|HL7Listener|HL7Listener|SOMEAPP|SOMEAPP|20198151353||ACK^A08||T|2.3\x1c\x0d MSA|AA|" + bytes(
            id, 'utf-8') + b" \x1c\x0d"

        clientSocket.send(ack)
Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
Tej gh
  • 31
  • 2

2 Answers2

2

I think your complete acknowledge is not being sent. You are using clientSocket.send(ack).

Use clientSocket.sendall(ack) instead.

Please refer to this answer from @kwarunek for more details.

socket.send is a low-level method and basically just the C/syscall method send(3) / send(2). It can send less bytes than you requested, but returns the number of bytes sent.

socket.sendall is a high-level Python-only method that sends the entire buffer you pass or throws an exception. It does that by calling socket.send until everything has been sent or an error occurs.

If you're using TCP with blocking sockets and don't want to be bothered by internals (this is the case for most simple network applications), use sendall.

Community
  • 1
  • 1
Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
-1

try adding enter in front of MSA|AA in the \n syntax I think it works

  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/30678156) – taylor.2317 Dec 29 '21 at 18:16