👋

【Python】asyncio で HTTP/2 フレームを送信する

2024/07/08に公開

スクリプトを連打してもたまにデータが壊れる程度であった

> python client.py

pri
data: '00001e0400000000000005001000000003000000fa000600100140000100001000000400100000000004080000000000000f0001'
size: 52
settings + ack
data: '000000040100000000'
size: 9
headers + data
data: '000030010400000001885f92497ca58ae819aafb50938ec415305a99567b5c01376196dd6d5f4a01d532db4282009a5042b8076e09953168df00000700010000000148656c6c6f0d0a'
size: 73
client.py
import asyncio

# https://gist.github.com/masakielastic/c955588fd4f94d7947dc848994694f14
from h2frames import h2frames

# h2c テストサーバー
# https://zenn.dev/masakielastic/articles/530f9751697ed6

async def write_frame():
    reader, writer = await asyncio.open_connection(
        '127.0.0.1', 8000)

    writer.write(h2frames('pri'))
    await writer.drain()

    data = await reader.read(128)
    print('pri')
    print(f'data: {data.hex()!r}')
    print(f'size: {len(data)!r}')

    writer.write(h2frames('settings'))
    await writer.drain()

    writer.write(h2frames('ack'))
    await writer.drain()

    data = await reader.read(128)
    print('settings + ack')
    print(f'data: {data.hex()!r}')
    print(f'size: {len(data)!r}')

    writer.write(h2frames('headers'))
    await writer.drain()

    data = await reader.read(256)
    print('headers + data')

    data = await reader.read(256)
    print('headers + data')
    print(f'data: {data.hex()!r}')
    print(f'size: {len(data)!r}')

    writer.close()
    await writer.wait_closed()

asyncio.run(write_frame())

Discussion