forked from ajdavis/coroutines-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
20.py
47 lines (39 loc) · 976 Bytes
/
20.py
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
from selectors import DefaultSelector, EVENT_WRITE
import socket
import time
selector = DefaultSelector()
n_jobs = 0
def get(path):
global n_jobs
n_jobs += 1
s = socket.socket()
s.setblocking(False)
try:
s.connect(('localhost', 5000))
except BlockingIOError:
pass
selector.register(s.fileno(), EVENT_WRITE, lambda: connected(s, path))
def connected(s, path):
global n_jobs
s.send(('GET %s HTTP/1.0\r\n\r\n' % path).encode())
buf = []
while True:
try:
chunk = s.recv(1000)
if not chunk:
break
buf.append(chunk)
except OSError:
pass
s.close()
print((b''.join(buf)).decode().split('\n')[0])
n_jobs -= 1
start = time.time()
get('/foo')
get('/bar')
while n_jobs:
events = selector.select()
for key, mask in events:
callback = key.data
callback()
print('took %.2f seconds' % (time.time() - start))