Created
February 15, 2021 08:07
-
-
Save kroggen/70fba39c6198391195bcbcc22c2dcd94 to your computer and use it in GitHub Desktop.
Length-prefix message framing in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import struct | |
def send_message(writer, message): | |
data = message.encode() | |
size = struct.pack('>L', len(data)) | |
writer.write(size + data) | |
async def receive_message(reader): | |
data = await reader.readexactly(4) | |
size = struct.unpack('>L', data)[0] | |
data = await reader.readexactly(size) | |
return data.decode() | |
async def tcp_echo_client(): | |
reader, writer = await asyncio.open_connection( | |
'127.0.0.1', 8888) | |
print('Sending first message') | |
send_message(writer, 'Hello...') | |
print('Sending second message') | |
send_message(writer, 'World!') | |
print(f'Awaiting response...') | |
message = await receive_message(reader) | |
print(f'Received: {message!r}') | |
message = await receive_message(reader) | |
print(f'Received: {message!r}') | |
print('Close the connection') | |
writer.close() | |
asyncio.run(tcp_echo_client()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import struct | |
def send_message(writer, message): | |
data = message.encode() | |
size = struct.pack('>L', len(data)) | |
writer.write(size + data) | |
async def receive_message(reader): | |
data = await reader.readexactly(4) | |
size = struct.unpack('>L', data)[0] | |
data = await reader.readexactly(size) | |
return data.decode() | |
async def handle_echo(reader, writer): | |
try: | |
while True: | |
message = await receive_message(reader) | |
addr = writer.get_extra_info('peername') | |
print(f"Received {message!r} from {addr!r}") | |
print(f"Send: {message!r}") | |
send_message(writer, message) | |
except: | |
await writer.drain() | |
print("Close the connection") | |
writer.close() | |
async def main(): | |
server = await asyncio.start_server( | |
handle_echo, '127.0.0.1', 8888) | |
addr = server.sockets[0].getsockname() | |
print(f'Serving on {addr}') | |
async with server: | |
await server.serve_forever() | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment