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
|
import socket
from time import time
import asyncio
HOST = '127.0.0.1'
PORT = 2045
start = time()
def get(path):
print('get {}'.format(path))
s = socket.socket()
s.connect((HOST, PORT))
s.sendall(path.encode())
chunk = s.recv(100)
print('get {}'.format(chunk.decode()))
def sync_call():
get('/bar')
get('/foo')
async def async_get(path):
print('get {}'.format(path))
reader, writer = await asyncio.open_connection(HOST, PORT)
writer.write(path.encode())
await writer.drain()
chunk = await reader.read(100)
print('get {}'.format(chunk.decode()))
def async_call():
loop = asyncio.get_event_loop()
t1 = loop.create_task(async_get('/bar'))
t2 = loop.create_task(async_get('/foo'))
loop.run_until_complete(asyncio.gather(t1, t2))
if __name__ == "__main__":
#sync_call()
async_call()
print('total {:.2f} seconds'.format(time() - start))
|