-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_server.py
More file actions
53 lines (45 loc) · 1.69 KB
/
test_server.py
File metadata and controls
53 lines (45 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Using the third party `aiorun` instead of the `asyncio.run()` to avoid
# boilerplate.
import aiorun
import asyncio
import hl7
from hl7.mllp import start_hl7_server
async def process_hl7_messages(hl7_reader, hl7_writer):
"""This will be called every time a socket connects
with us.
"""
peername = hl7_writer.get_extra_info("peername")
print(f"Connection established {peername}")
try:
# We're going to keep listening until the writer
# is closed. Only writers have closed status.
while not hl7_writer.is_closing():
hl7_message = await hl7_reader.readmessage()
print(f'Received message\n {hl7_message}'.replace('\r', '\n'))
# Now let's send the ACK and wait for the
# writer to drain
hl7_writer.writemessage(hl7_message.create_ack())
await hl7_writer.drain()
except asyncio.IncompleteReadError:
# Oops, something went wrong, if the writer is not
# closed or closing, close it.
if not hl7_writer.is_closing():
hl7_writer.close()
await hl7_writer.wait_closed()
print(f"Connection closed {peername}")
async def main():
try:
# Start the server in a with clause to make sure we
# close it
async with await start_hl7_server(
process_hl7_messages, port=2577
) as hl7_server:
# And now we server forever. Or until we are
# cancelled...
await hl7_server.serve_forever()
except asyncio.CancelledError:
# Cancelled errors are expected
pass
except Exception:
print("Error occurred in main")
aiorun.run(main(), stop_on_unhandled_errors=True)