import asyncio
@asyncio.coroutine
def wget(host):
print (‘wget %s....‘ % host)
connect = asyncio.open_connection(host,80)
reader,writer = yield from connect
# header = ‘GET / HTTP/1.0\r\nHost: %s\r\n\r\n‘ % host
header = ‘GET / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n‘ % host
writer.write(header.encode(‘utf-8‘))
yield from writer.drain()
while True:
line = yield from reader.readline()
if line == b‘\r\n‘:
break
print (‘%s header > %s ‘ % (host,line.decode(‘utf-8‘).rstrip()))
writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in [‘www.sina.com.cn‘,‘www.sohu.com‘,‘www.163.com‘]]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
‘‘‘
wget www.163.com...
wget www.sohu.com...
wget www.sina.com.cn...
www.sohu.com header > HTTP/1.1 200 OK
www.sohu.com header > Content-Type: text/html;charset=UTF-8
www.sohu.com header > Connection: close
www.sohu.com header > Server: nginx
www.sohu.com header > Date: Tue, 31 Jul 2018 07:44:25 GMT
www.sohu.com header > Cache-Control: max-age=60
www.sohu.com header > X-From-Sohu: X-SRC-Cached
www.sohu.com header > Content-Encoding: gzip
www.sohu.com header > FSS-Cache: HIT from 10983758.13343064.18921842
www.sohu.com header > FSS-Proxy: Powered by 9541944.10459458.17480006
www.sina.com.cn header > HTTP/1.1 302 Moved Temporarily
www.sina.com.cn header > Server: nginx
www.sina.com.cn header > Date: Tue, 31 Jul 2018 07:45:18 GMT
www.sina.com.cn header > Content-Type: text/html
www.sina.com.cn header > Content-Length: 154
www.sina.com.cn header > Connection: close
www.sina.com.cn header > Location: https://www.sina.com.cn/
www.sina.com.cn header > X-Via-CDN: f=edge,s=ctc.nanjing.ha2ts4.118.nb.sinaedge.com,c=180.168.212.46;
www.sina.com.cn header > X-Via-Edge: 15330231186532ed4a8b47c5e66ca7c92596e
www.163.com header > HTTP/1.1 200 OK
www.163.com header > Expires: Tue, 31 Jul 2018 07:46:38 GMT
www.163.com header > Date: Tue, 31 Jul 2018 07:45:18 GMT
www.163.com header > Server: nginx
www.163.com header > Content-Type: text/html; charset=GBK
www.163.com header > Vary: Accept-Encoding,User-Agent,Accept
www.163.com header > Cache-Control: max-age=80
www.163.com header > X-Via: 1.1 PSzjwzdx11jb78:2 (Cdn Cache Server V2.0), 1.1 zhoudianxin177:0 (Cdn Cache Server V2.0)
www.163.com header > Connection: close
‘‘‘
‘‘‘
【解析】
asyncio.open_connection接受host参数和port参数以及一些可选的关键字参数.返回一个reader和一个writer,redaer is a StreamReader instance; the writer is a StreamWriter instance.
writer.write就和socket.send差不多…
drain的官方解释:
drain() gives the opportunity for the loop to schedule the write operation and flush the buffer. It should especially be used when a possibly large amount of data is written to the transport, and the coroutine does not yield-from between calls to write().
在事件循环中刷新缓冲区,特别是在数据量很大的情况下,保证数据完整性
‘‘‘【Python】【廖雪峰笔记】【协程】
原文:https://www.cnblogs.com/suren2017/p/9397506.html