跟老菜鸟学python
http://edu.csdn.net/course/detail/2592
在这例子里,先导入库asyncio和logging,接着导入系统库sys。
然后定义发送的数据MESSAGES,服务器的IP和端口。定义一个协程函数echo_client,在这个函数使用asyncio.open_connection来连接服务器,创建一个socket,返回两个对应的流控制对象StreamReader、StreamWriter。
后面就使用这两个对象来进行与服务器交互,接着调用写对象write函数来发送数据给服务器,但是这里并没有直正把数据发送出去,只是写到内部缓冲区,因此调用writer.drain()函数就是等着socket把数据发送出去。
最后就是接收数据的无限循环,reader.read()函数就是从服务器接收数据。如果无数据接收到,就结束循环。
源码如下:
import asyncio
import logging
import sys
MESSAGES = [
b'This is the message. ',
b'It will be sent ',
b'in parts.',
]
SERVER_ADDRESS = ('localhost', 10000)
async def echo_client(address, messages):
log = logging.getLogger('echo_client')
log.debug('connecting to {} port {}'.format(*address))
reader, writer = await asyncio.open_connection(*address)
# This could be writer.writelines() except that
# would make it harder to show each part of the message
# being sent.
for msg in messages:
writer.write(msg)
log.debug('sending {!r}'.format(msg))
if writer.can_write_eof():
writer.write_eof()
await writer.drain()
log.debug('waiting for response')
while True:
data = await reader.read(128)
if data:
log.debug('received {!r}'.format(data))
else:
log.debug('closing')
writer.close()
return
logging.basicConfig(
level=logging.DEBUG,
format='%(name)s: %(message)s',
stream=sys.stderr,
)
log = logging.getLogger('main')
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(
echo_client(SERVER_ADDRESS, MESSAGES)
)
finally:
log.debug('closing event loop')
event_loop.close()
输出如下:
asyncio: Using selector: SelectSelector
echo_client: connecting to localhost port 10000
echo_client: sending b'This is the message. '
echo_client: sending b'It will be sent '
echo_client: sending b'in parts.'
echo_client: waiting for response
echo_client: received b'This is the message. It will be sent in parts.'
echo_client: closing
main: closing event loop