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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
| import asyncio
import aiohttp
class HTTP2Multiplexing:
def __init__(self, base_url):
self.base_url = base_url
self.session = None
async def create_session(self):
"""Create HTTP/2 session"""
connector = aiohttp.TCPConnector(
limit=100,
limit_per_host=30,
ttl_dns_cache=300,
use_dns_cache=True
)
self.session = aiohttp.ClientSession(
connector=connector,
timeout=aiohttp.ClientTimeout(total=30)
)
async def send_multiple_requests(self, requests):
"""Send multiple simultaneous requests"""
if not self.session:
await self.create_session()
# Create tasks for simultaneous requests
tasks = []
for method, path, headers in requests:
task = self.send_request(method, path, headers)
tasks.append(task)
# Execute simultaneous requests
responses = await asyncio.gather(*tasks)
return responses
async def send_request(self, method, path, headers=None):
"""Send individual request"""
url = f"{self.base_url}{path}"
async with self.session.request(
method,
url,
headers=headers
) as response:
data = await response.text()
return {
'status': response.status,
'headers': dict(response.headers),
'data': data
}
async def close(self):
"""Close session"""
if self.session:
await self.session.close()
# Usage example
async def test_multiplexing():
client = HTTP2Multiplexing('https://httpbin.org')
# Multiple simultaneous requests
requests = [
('GET', '/get', {}),
('GET', '/headers', {}),
('GET', '/user-agent', {}),
('GET', '/ip', {}),
('GET', '/json', {})
]
responses = await client.send_multiple_requests(requests)
for i, response in enumerate(responses):
print(f"Request {i+1}: {response['status']}")
await client.close()
# asyncio.run(test_multiplexing())
|