问题描述
我正在尝试在 python 中创建 HL7 侦听器.我可以通过 socket 接收消息,但无法发送有效确认
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 代码:
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)
推荐答案
我认为您的完整确认未发送.您正在使用 clientSocket.send(ack)
.
I think your complete acknowledge is not being sent. You are using clientSocket.send(ack)
.
改用clientSocket.sendall(ack)
.
请参阅@kwarunek 的此回答以了解更多详情.
Please refer to this answer from @kwarunek for more details.
socket.send 是一种低级方法,基本上只是 C/syscall 方法 发送(3)/发送(2).它可以发送比您请求的更少的字节,但返回发送的字节数.
socket.sendall 是一种高级 Python 专用方法,它发送您传递的整个缓冲区或引发异常.它通过调用 socket.send
直到所有内容都已发送或发生错误来做到这一点.
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.
如果您使用带有阻塞套接字的 TCP 并且不想被内部结构打扰(大多数简单的网络应用程序都是这种情况),请使用 sendall
.
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
.
这篇关于Python HL7 侦听器套接字消息确认的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!