search
HomeBackend DevelopmentPython Tutorial探索Python3.4中新引入的asyncio模块

使用 Simple Protocol

asyncio.BaseProtocol 类是asyncio模块中协议接口(protocol interface)的一个常见的基类。asyncio.Protocolclass 继承自asyncio.BaseProtocol 并为stream protocols提供了一个接口。下面的代码演示了asyncio.Protocol 接口的一个简单实现,它的行为1就像一个echo server,同时,它还会在Python的控制台中输出一些信息。SimpleEchoProtocol 继承自asyncio.Protocol,并且实现了3个方法:connection_made, data_received 以及 andconnection_lost:

import asyncio
 
class SimpleEchoProtocol(asyncio.Protocol):
  def connection_made(self, transport):
    """
    Called when a connection is made.
    The argument is the transport representing the pipe connection.
    To receive data, wait for data_received() calls.
    When the connection is closed, connection_lost() is called.
    """
    print("Connection received!")
    self.transport = transport
 
  def data_received(self, data):
    """
    Called when some data is received.
    The argument is a bytes object.
    """
    print(data)
    self.transport.write(b'echo:')
    self.transport.write(data)
 
  def connection_lost(self, exc):
    """
    Called when the connection is lost or closed.
    The argument is an exception object or None (the latter
    meaning a regular EOF is received or the connection was
    aborted or closed).
    """
    print("Connection lost! Closing server...")
    server.close()
 
loop = asyncio.get_event_loop()
server = loop.run_until_complete(loop.create_server(SimpleEchoProtocol, 'localhost', 2222))
loop.run_until_complete(server.wait_closed())

你可以通过运行一个telnet客户端程序,并且连接到localhost的2222端口来测试这个echo server。如果你正在使用这个端口,你可以将这个端口号修改为任何其他可以使用的端口。如果你使用默认的值,你可以在Python的控制台中运行上面的代码,之后在命令提示符或终端中运行 telnet localhost 2222。你将会看到 Connection received! 的信息显示在Python的控制台中。接下来,你在telnet的控制台中输入的任何字符都会以echo:跟上输入的字符的形式展示出来,同时,在Python的控制台中会显示出刚才新输入的字符。当你退出telnet控制台时,你会看到Connection lost! Closing server... 的信息展示在Python的控制台中。

举个例子,如果你在开启telnet之后输入 abc,你将会在telnet的窗口中看到下面的消息:

 echo:abecho:bcecho:c

此外,在Python的控制台中会显示下面的消息:

 Connection received!
 b'a'
 b'b'
 b'c'
 Connection lost! Closing server...

在创建了一个名为loop的事件循环之后,代码将会调用loop.run_until_complete来运行loop.create_server这个协程(coroutine)。这个协程创建了一个TCP服务器并使用protocol的工厂类绑定到指定主机的指定端口(在这个例子中是localhost上的2222端口,使用的工厂类是SimpleEchoProtocol)并返回一个Server的对象,以便用来停止服务。代码将这个实例赋值给server变量。用这种方式,当建立一个客户端连接时,会创建一个新的SimpleEchoProtocol的实例并且该类中的方法会被执行。

当成功的创建了一个连接之后,connection_made 方法里面的代码输出了一条消息,并将收到的内容作为一个参数赋值给transport成员变量,以便稍后在另一个方法中使用。

当收到了传来的数据时,data_received方面里面的代码会将收到的数据字节输出,并且通过调用两次self.transport.write 方法将echo: 和收到数据发送给客户端。当然了,也可以只调用一次self.transport.write将所有的数据返回,但是我想更清楚的将发送echo:的代码和发送收到的数据的代码区分开来。

当连接关掉或者断开时,connection_lost方法中的代码将会输出一条消息,并且调用server.close();此时,那个在服务器关闭前一直运行的循环停止了运行。
使用 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())

你可以在不同的Python控制台中执行客户端的代码。如果服务端正在运行,控制台中会输出下面的内容:

Lines received
b'First line.\n'
b'Second line.\n'
b'Third line.\n'
b'Last line.\n'

执行服务端代码的Python控制台会显示下面的内容:

 Connection received!
 b'First line.\nSecond line.\nThird line.\nLast line.\n'

首先,让我们关注一下服务端的代码。在创建完一个叫loop的事件循环之后,代码会调用loop.run_until_complete来运行这个simple_echo_server协程。该协程调用asyncio.start_server协程来开启一个socket服务器,绑定到指定的主机和端口号,之后,对每一个客户端连接执行作为参数传入的回调函数——client_connected_handler。在这个例子中,client_connected_handler是另一个协程,并且不会被自动的转换为一个Task。除了协程(coroutine)之外,你可以指定一个普通的回调函数。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),