0
# Connection Management
1
2
Core HTTP/2 connection handling providing the primary interface for all HTTP/2 protocol operations. The H2Connection class manages connection state, frame processing, stream lifecycle, and data transmission.
3
4
## Capabilities
5
6
### H2Connection Class
7
8
The main connection object that handles HTTP/2 protocol operations, maintains connection and stream state, and processes frames according to the HTTP/2 specification.
9
10
```python { .api }
11
class H2Connection:
12
def __init__(self, config: H2Configuration | None = None):
13
"""
14
Initialize HTTP/2 connection.
15
16
Args:
17
config: Connection configuration object
18
"""
19
```
20
21
#### Properties
22
23
Connection state properties providing information about open streams and flow control.
24
25
```python { .api }
26
@property
27
def open_outbound_streams(self) -> int:
28
"""The current number of open outbound streams."""
29
30
@property
31
def open_inbound_streams(self) -> int:
32
"""The current number of open inbound streams."""
33
34
@property
35
def inbound_flow_control_window(self) -> int:
36
"""The size of the inbound flow control window for the connection."""
37
```
38
39
### Connection Initialization
40
41
Methods for establishing HTTP/2 connections in different scenarios.
42
43
```python { .api }
44
def initiate_connection(self) -> None:
45
"""
46
Provides any data that needs to be sent at the start of the connection.
47
Must be called for both clients and servers.
48
"""
49
50
def initiate_upgrade_connection(self, settings_header: bytes | None = None) -> bytes | None:
51
"""
52
Call to initialise the connection object for use with an upgraded HTTP/2
53
connection (i.e. a connection negotiated using the Upgrade: h2c HTTP header).
54
55
Args:
56
settings_header: HTTP2-Settings header value from HTTP/1.1 upgrade request
57
58
Returns:
59
Connection preface to send to the client, or None if not applicable
60
"""
61
```
62
63
### Stream Management
64
65
Methods for creating, managing, and controlling HTTP/2 streams.
66
67
```python { .api }
68
def get_next_available_stream_id(self) -> int:
69
"""
70
Returns an integer suitable for use as the stream ID for the next stream
71
created by this endpoint. For server endpoints, this stream ID will be even.
72
For client endpoints, this stream ID will be odd.
73
"""
74
75
def send_headers(
76
self,
77
stream_id: int,
78
headers: Iterable[HeaderWeaklyTyped],
79
end_stream: bool = False,
80
priority_weight: int | None = None,
81
priority_depends_on: int | None = None,
82
priority_exclusive: bool | None = None
83
) -> None:
84
"""
85
Send headers on a given stream. This function can be used to send
86
request or response headers.
87
88
Args:
89
stream_id: Stream ID to send headers on
90
headers: List of (name, value) header tuples
91
end_stream: Whether to close stream after sending headers
92
priority_weight: Stream priority weight (1-256)
93
priority_depends_on: Stream ID this stream depends on
94
priority_exclusive: Whether dependency is exclusive
95
"""
96
97
def send_data(
98
self,
99
stream_id: int,
100
data: bytes | memoryview,
101
end_stream: bool = False,
102
pad_length: Any = None
103
) -> None:
104
"""
105
Send data on a given stream. This method does no breaking up of data.
106
107
Args:
108
stream_id: Stream ID to send data on
109
data: Data bytes to send
110
end_stream: Whether to close stream after sending data
111
pad_length: Padding length for data frame
112
"""
113
114
def end_stream(self, stream_id: int) -> None:
115
"""
116
Cleanly end a given stream. This method ends a stream by sending an
117
empty DATA frame on that stream with the END_STREAM flag set.
118
119
Args:
120
stream_id: Stream ID to end
121
"""
122
123
def push_stream(
124
self,
125
stream_id: int,
126
promised_stream_id: int,
127
request_headers: Iterable[HeaderWeaklyTyped]
128
) -> None:
129
"""
130
Push a response to the client by sending a PUSH_PROMISE frame.
131
132
Args:
133
stream_id: Stream ID to send push promise on
134
promised_stream_id: Stream ID for the promised response
135
request_headers: Headers for the promised request
136
"""
137
138
def reset_stream(self, stream_id: int, error_code: ErrorCodes | int = 0) -> None:
139
"""
140
Reset a stream. This method forcibly closes a stream by sending a
141
RST_STREAM frame for a given stream.
142
143
Args:
144
stream_id: Stream ID to reset
145
error_code: HTTP/2 error code for reset reason
146
"""
147
```
148
149
### Flow Control
150
151
Methods for managing HTTP/2 flow control windows at connection and stream levels.
152
153
```python { .api }
154
def increment_flow_control_window(self, increment: int, stream_id: int | None = None) -> None:
155
"""
156
Increment a flow control window, optionally for a single stream.
157
Allows the remote peer to send more data.
158
159
Args:
160
increment: Number of bytes to increment window by
161
stream_id: Stream ID to increment window for, or None for connection window
162
"""
163
164
def local_flow_control_window(self, stream_id: int) -> int:
165
"""
166
Returns the maximum amount of data that can be sent on stream stream_id.
167
168
Args:
169
stream_id: Stream ID to check window for
170
171
Returns:
172
Number of bytes that can be sent
173
"""
174
175
def remote_flow_control_window(self, stream_id: int) -> int:
176
"""
177
Returns the maximum amount of data the remote peer can send on stream stream_id.
178
179
Args:
180
stream_id: Stream ID to check window for
181
182
Returns:
183
Number of bytes remote peer can send
184
"""
185
186
def acknowledge_received_data(self, acknowledged_size: int, stream_id: int) -> None:
187
"""
188
Inform the H2Connection that a certain number of flow-controlled bytes have
189
been processed, and that the space should be handed back to the remote peer
190
at an opportune time.
191
192
Args:
193
acknowledged_size: Number of bytes processed
194
stream_id: Stream ID the data was received on
195
"""
196
```
197
198
### Connection Control
199
200
Methods for connection-level operations including ping, settings, and connection termination.
201
202
```python { .api }
203
def ping(self, opaque_data: bytes | str) -> None:
204
"""
205
Send a PING frame.
206
207
Args:
208
opaque_data: 8 bytes of opaque data to include in ping
209
"""
210
211
def close_connection(
212
self,
213
error_code: ErrorCodes | int = 0,
214
additional_data: bytes | None = None,
215
last_stream_id: int | None = None
216
) -> None:
217
"""
218
Close a connection, emitting a GOAWAY frame.
219
220
Args:
221
error_code: HTTP/2 error code for connection close reason
222
additional_data: Additional debug data
223
last_stream_id: Last stream ID processed
224
"""
225
226
def update_settings(self, new_settings: dict[SettingCodes | int, int]) -> None:
227
"""
228
Update the local settings. This will prepare and emit the appropriate SETTINGS frame.
229
230
Args:
231
new_settings: Dictionary of setting codes to values
232
"""
233
234
def advertise_alternative_service(
235
self,
236
field_value: bytes | str,
237
origin: bytes | None = None,
238
stream_id: int | None = None
239
) -> None:
240
"""
241
Notify a client about an available Alternative Service.
242
243
Args:
244
field_value: Alt-Svc field value as defined in RFC 7838
245
origin: Origin to advertise alt-svc for
246
stream_id: Stream ID to send alt-svc on, or None for connection level
247
"""
248
249
def prioritize(
250
self,
251
stream_id: int,
252
weight: int | None = None,
253
depends_on: int | None = None,
254
exclusive: bool | None = None
255
) -> None:
256
"""
257
Notify a server about the priority of a stream.
258
259
Args:
260
stream_id: Stream ID to set priority for
261
weight: Stream priority weight (1-256)
262
depends_on: Stream ID this stream depends on
263
exclusive: Whether dependency is exclusive
264
"""
265
```
266
267
### Data Handling
268
269
Methods for sending and receiving data through the connection.
270
271
```python { .api }
272
def data_to_send(self, amount: int | None = None) -> bytes:
273
"""
274
Returns some data for sending out of the internal data buffer. This method is
275
analogous to read on a file-like object, but it doesn't block.
276
277
Args:
278
amount: Maximum number of bytes to return, or None for all available
279
280
Returns:
281
Bytes to send over the network connection
282
"""
283
284
def clear_outbound_data_buffer(self) -> None:
285
"""
286
Clears the outbound data buffer, such that if this call was immediately
287
followed by a call to data_to_send, that call would return no data.
288
"""
289
290
def receive_data(self, data: bytes) -> list[Event]:
291
"""
292
Pass some received HTTP/2 data to the connection for handling.
293
294
Args:
295
data: Raw bytes received from the network
296
297
Returns:
298
List of events generated from processing the data
299
"""
300
```
301
302
## Usage Examples
303
304
### Basic Client Connection
305
306
```python
307
from h2.connection import H2Connection
308
from h2.config import H2Configuration
309
310
# Create client connection
311
config = H2Configuration(client_side=True)
312
conn = H2Connection(config=config)
313
314
# Initialize connection
315
conn.initiate_connection()
316
data_to_send = conn.data_to_send()
317
# Send data_to_send over your socket
318
319
# Send request
320
conn.send_headers(
321
stream_id=1,
322
headers=[
323
(':method', 'GET'),
324
(':path', '/api/data'),
325
(':scheme', 'https'),
326
(':authority', 'example.com'),
327
]
328
)
329
data_to_send = conn.data_to_send()
330
# Send data_to_send over your socket
331
```
332
333
### Flow Control Management
334
335
```python
336
# Process received data and manage flow control
337
received_data = socket.recv(65536)
338
events = conn.receive_data(received_data)
339
340
for event in events:
341
if isinstance(event, DataReceived):
342
# Process the data
343
process_data(event.data)
344
345
# Acknowledge received data for flow control
346
conn.acknowledge_received_data(
347
acknowledged_size=len(event.data),
348
stream_id=event.stream_id
349
)
350
351
# Send acknowledgment
352
data_to_send = conn.data_to_send()
353
socket.send(data_to_send)
354
```