Skip to content

Commit 1f1d535

Browse files
committed
add async http client
1 parent 59d1de9 commit 1f1d535

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

py3/coroutine/async_wget.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import asyncio
5+
6+
@asyncio.coroutine
7+
def wget(host):
8+
print('wget %s...' % host)
9+
connect = asyncio.open_connection(host, 80)
10+
reader, writer = yield from connect
11+
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
12+
writer.write(header.encode('utf-8'))
13+
yield from writer.drain()
14+
while True:
15+
line = yield from reader.readline()
16+
if line == b'\r\n':
17+
break
18+
print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
19+
# Ignore the body, close the socket
20+
writer.close()
21+
22+
loop = asyncio.get_event_loop()
23+
tasks = [asyncio.async(wget(host)) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
24+
for task in tasks:
25+
loop.run_until_complete(task)
26+
loop.close()

0 commit comments

Comments
 (0)