Skip to content

Instantly share code, notes, and snippets.

@kroggen
Created February 15, 2021 08:07
Show Gist options
  • Save kroggen/70fba39c6198391195bcbcc22c2dcd94 to your computer and use it in GitHub Desktop.
Save kroggen/70fba39c6198391195bcbcc22c2dcd94 to your computer and use it in GitHub Desktop.
Length-prefix message framing in Python
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())
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