Skip to content

Commit

Permalink
Merge pull request #2 from csunny/async
Browse files Browse the repository at this point in the history
asyncio lib tcp server
  • Loading branch information
csunny authored Nov 27, 2018
2 parents c5fb17e + 736bb74 commit 2184768
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
28 changes: 28 additions & 0 deletions examples/async_wget.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/usr/bin/env python3

import asyncio

async def wget(host):
print("wget %s ...", host)
connect = asyncio.open_connection(host, 80)
reader, writer = await connect

header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
writer.write(header.encode())
await writer.drain()

while True:
line = await reader.readline()
if line == b'\r\n':
break
print("%s header > %s" % (host, line.decode().rstrip()))

writer.close()


loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ["www.sina.com", "www.sohu.com", "www.163.com"]]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()


20 changes: 20 additions & 0 deletions examples/echo/async_tcp_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/usr/bin/env python3

import asyncio

async def echo_tcp_client(message, loop):
reader, writer = await asyncio.open_connection('127.0.0.1', 8888, loop=loop)

print("发送数据: %r" % message)
writer.write(message.encode())

data = await reader.read(100)
print("接收数据: %r" % data.decode())

print("关闭socket连接")
writer.close()

message = "Hello World!"
loop = asyncio.get_event_loop()
loop.run_until_complete(echo_tcp_client(message, loop))
loop.close()
30 changes: 30 additions & 0 deletions examples/echo/async_tcp_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/usr/bin/env python3

import asyncio

async def handle_echo(reader, writer):

data = await reader.read(100)

message = data.decode()
addr = writer.get_extra_info('peername')
print("> 接收到数据 %r From %r" % (message, addr))

print("> 发送数据: %r" % message)
writer.write(data)
await writer.drain()
writer.close()

loop = asyncio.get_event_loop()
coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop)
server = loop.run_until_complete(coro)
print('Serving on {}'.format(server.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass


server.close()
loop.run_until_complete(server.wait_closed())
loop.close()

0 comments on commit 2184768

Please sign in to comment.