【分享】Python 3.4.3之asyncio tcp server

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【分享】Python 3.4.3之asyncio tcp server

Server端:

import asyncio

@asyncio.coroutine
def handle_echo(reader, writer):
    data = yield from reader.read(100)
    message = data.decode()
    addr = writer.get_extra_info('peername')
    print("Received %r from %r" % (message, addr))

    print("Send: %r" % message)
    writer.write(data)
    yield from writer.drain()

    print("Close the client socket")
    writer.close()

loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo, '127.0.0.1', 9999, loop=loop)
server = loop.run_until_complete(coro)

# Serve requests until Ctrl+C is pressed
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass

# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()

Client端:

import asyncio

import asyncio

@asyncio.coroutine
def tcp_echo_client(message, loop):
	reader, writer = yield from asyncio.open_connection('127.0.0.1', 9999,
                                                   loop=loop)

	print('Send: %r' % message)
	writer.write(message.encode())

	data = yield from reader.read(100)
	print('Received: %r' % data.decode())

	print('Close the socket')
	writer.close()


message = 'Hello World!'
loop = asyncio.get_event_loop()
loop.run_until_complete(tcp_echo_client(message, loop))
loop.close()

演示:

asyncio

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【分享】Python 3.4.3之asyncio tcp server

文章的脚注信息由WordPress的wp-posturl插件自动生成



|2|left
打赏

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: