python asyncio tcp server_Python 3.4 中新的 asyncio : Servers、Protocols 和 Transports

使用 Clients and Servers

在上面的例子中,telnet是一个客户端。asyncio模块提供了一个协程方便你很容易的使用stream reader 和 writer来编写服务端和客户端。下面的代码演示了一个简单的echo server,该server监听localhost上的2222端口。你可以在Python的控制台中运行下面的代码,之后在另一个Python的控制台中运行客户端的代码作为客户端。

import asyncio

@asyncio.coroutine

def simple_echo_server():

# Start a socket server, call back for each client connected.

# The client_connected_handler coroutine will be automatically converted to a Task

yield from asyncio.start_server(client_connected_handler, 'localhost', 2222)

@asyncio.coroutine

def client_connected_handler(client_reader, client_writer):

# Runs for each client connected

# client_reader is a StreamReader object

# client_writer is a StreamWriter object

print("Connection received!")

while True:

data = yield from client_reader.read(8192)

if not data:

break

print(data)

client_writer.write(data)

loop = asyncio.get_event_loop()

loop.run_until_complete(simple_echo_server())

try:

loop.run_forever()

finally:

loop.close()

下面的代码演示了一个客户端程序连接了localhost上的2222端口,并且使用asyncio.StreamWriter对象写了几行数据,之后使用asyncio.StreamWriter对象读取服务端返回的数据。

import asyncio

LASTLINE = b'Last line.\n'

@asyncio.coroutine

def simple_echo_client():

# Open a connection and write a few lines by using the StreamWriter object

reader, writer = yield from asyncio.open_connection('localhost', 2222)

# reader is a StreamReader object

# writer is a StreamWriter object

writer.write(b'First line.\n')

writer.write(b'Second line.\n')

writer.write(b'Third line.\n')

writer.write(LASTLINE)

# Now, read a few lines by using the StreamReader object

print("Lines received")

while True:

line = yield from reader.readline()

print(line)

if line == LASTLINE or not line:

break

writer.close()

loop = asyncio.get_event_loop()

loop.run_until_complete(simple_echo_client())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值