# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001 Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # Rafael Fontenelle , 2026 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.14\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2026-05-08 19:31+0000\n" "PO-Revision-Date: 2026-05-08 17:17+0000\n" "Last-Translator: Rafael Fontenelle , 2026\n" "Language-Team: Chinese (China) (https://app.transifex.com/python-doc/teams/5390/zh_CN/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh_CN\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../library/asyncio-protocol.rst:9 msgid "Transports and Protocols" msgstr "传输和协议" #: ../../library/asyncio-protocol.rst:12 msgid "Preface" msgstr "前言" #: ../../library/asyncio-protocol.rst:13 msgid "" "Transports and Protocols are used by the **low-level** event loop APIs such " "as :meth:`loop.create_connection`. They use callback-based programming " "style and enable high-performance implementations of network or IPC " "protocols (e.g. HTTP)." msgstr "" "传输和协议会被像 :meth:`loop.create_connection` 这类 **底层** " "事件循环接口使用。它们使用基于回调的编程风格支持网络或 IPC 协议(如 HTTP)的高性能实现。" #: ../../library/asyncio-protocol.rst:18 msgid "" "Essentially, transports and protocols should only be used in libraries and " "frameworks and never in high-level asyncio applications." msgstr "基本上,传输和协议应只在库和框架上使用,而不应该在高层的异步应用中使用它们。" #: ../../library/asyncio-protocol.rst:22 msgid "This documentation page covers both `Transports`_ and `Protocols`_." msgstr "本文档包含 `Transports`_ 和 `Protocols`_。" #: ../../library/asyncio-protocol.rst:25 msgid "Introduction" msgstr "概述" #: ../../library/asyncio-protocol.rst:26 msgid "" "At the highest level, the transport is concerned with *how* bytes are " "transmitted, while the protocol determines *which* bytes to transmit (and to" " some extent when)." msgstr "在最顶层,传输只关心 **怎样** 传送字节内容,而协议决定传送 **哪些** 字节内容 (还要在一定程度上考虑何时)。" #: ../../library/asyncio-protocol.rst:30 msgid "" "A different way of saying the same thing: a transport is an abstraction for " "a socket (or similar I/O endpoint) while a protocol is an abstraction for an" " application, from the transport's point of view." msgstr "也可以这样说:从传输的角度来看,传输是套接字 (或类似的 I/O 终端) 的抽象,而协议是应用程序的抽象。" #: ../../library/asyncio-protocol.rst:35 msgid "" "Yet another view is the transport and protocol interfaces together define an" " abstract interface for using network I/O and interprocess I/O." msgstr "换另一种说法,传输和协议一起定义网络 I/O 和进程间 I/O 的抽象接口。" #: ../../library/asyncio-protocol.rst:39 msgid "" "There is always a 1:1 relationship between transport and protocol objects: " "the protocol calls transport methods to send data, while the transport calls" " protocol methods to pass it data that has been received." msgstr "传输对象和协议对象总是一对一关系:协议调用传输方法来发送数据,而传输在接收到数据时调用协议方法传递数据。" #: ../../library/asyncio-protocol.rst:44 msgid "" "Most of connection oriented event loop methods (such as " ":meth:`loop.create_connection`) usually accept a *protocol_factory* argument" " used to create a *Protocol* object for an accepted connection, represented " "by a *Transport* object. Such methods usually return a tuple of " "``(transport, protocol)``." msgstr "" "大部分面向连接的事件循环方法 (如 :meth:`loop.create_connection` ) 通常接受 *protocol_factory* " "参数为接收到的连接创建 *协议* 对象,并用 *传输* 对象来表示。这些方法一般会返回 ``(transport, protocol)`` 元组。" #: ../../library/asyncio-protocol.rst:51 msgid "Contents" msgstr "目录" #: ../../library/asyncio-protocol.rst:52 msgid "This documentation page contains the following sections:" msgstr "本文档包含下列小节:" #: ../../library/asyncio-protocol.rst:54 msgid "" "The `Transports`_ section documents asyncio :class:`BaseTransport`, " ":class:`ReadTransport`, :class:`WriteTransport`, :class:`Transport`, " ":class:`DatagramTransport`, and :class:`SubprocessTransport` classes." msgstr "" "`Transports`_ 部分记载 asyncio :class:`BaseTransport`、 :class:`ReadTransport`、 " ":class:`WriteTransport`、 :class:`Transport`、 :class:`DatagramTransport` 和 " ":class:`SubprocessTransport` 等类。" #: ../../library/asyncio-protocol.rst:59 msgid "" "The `Protocols`_ section documents asyncio :class:`BaseProtocol`, " ":class:`Protocol`, :class:`BufferedProtocol`, :class:`DatagramProtocol`, and" " :class:`SubprocessProtocol` classes." msgstr "" "`Protocols`_ 部分记载 asyncio :class:`BaseProtocol`、 :class:`Protocol`、 " ":class:`BufferedProtocol`、 :class:`DatagramProtocol` 和 " ":class:`SubprocessProtocol` 等类。" #: ../../library/asyncio-protocol.rst:63 msgid "" "The `Examples`_ section showcases how to work with transports, protocols, " "and low-level event loop APIs." msgstr "`Examples`_ 部分展示怎样使用传输、协议和底层事件循环接口。" #: ../../library/asyncio-protocol.rst:70 msgid "Transports" msgstr "传输" #: ../../library/asyncio-protocol.rst:72 msgid "**Source code:** :source:`Lib/asyncio/transports.py`" msgstr "**源码:** :source:`Lib/asyncio/transports.py`" #: ../../library/asyncio-protocol.rst:76 msgid "" "Transports are classes provided by :mod:`asyncio` in order to abstract " "various kinds of communication channels." msgstr "传输属于 :mod:`asyncio` 模块中的类,用来抽象各种通信通道。" #: ../../library/asyncio-protocol.rst:79 msgid "" "Transport objects are always instantiated by an :ref:`asyncio event loop " "`." msgstr "传输对象总是由 :ref:`异步 IO 事件循环 ` 实例化。" #: ../../library/asyncio-protocol.rst:82 msgid "" "asyncio implements transports for TCP, UDP, SSL, and subprocess pipes. The " "methods available on a transport depend on the transport's kind." msgstr "异步 IO 实现 TCP、UDP、SSL 和子进程管道的传输。传输上可用的方法由传输的类型决定。" #: ../../library/asyncio-protocol.rst:85 msgid "" "The transport classes are :ref:`not thread safe `." msgstr "传输类属于 :ref:`线程不安全`。" #: ../../library/asyncio-protocol.rst:89 msgid "Transports Hierarchy" msgstr "传输层级" #: ../../library/asyncio-protocol.rst:93 msgid "" "Base class for all transports. Contains methods that all asyncio transports" " share." msgstr "所有传输的基类。包含所有异步 IO 传输共用的方法。" #: ../../library/asyncio-protocol.rst:98 msgid "A base transport for write-only connections." msgstr "只写连接的基础传输。" #: ../../library/asyncio-protocol.rst:100 msgid "" "Instances of the *WriteTransport* class are returned from the " ":meth:`loop.connect_write_pipe` event loop method and are also used by " "subprocess-related methods like :meth:`loop.subprocess_exec`." msgstr "" "*WriteTransport* 类的实例由 :meth:`loop.connect_write_pipe` 事件循环方法返回,也被子进程相关的方法如 " ":meth:`loop.subprocess_exec` 使用。" #: ../../library/asyncio-protocol.rst:107 msgid "A base transport for read-only connections." msgstr "只读连接的基础传输。" #: ../../library/asyncio-protocol.rst:109 msgid "" "Instances of the *ReadTransport* class are returned from the " ":meth:`loop.connect_read_pipe` event loop method and are also used by " "subprocess-related methods like :meth:`loop.subprocess_exec`." msgstr "" "*ReadTransport* 类的实例由 :meth:`loop.connect_read_pipe` 事件循环方法返回,也被子进程相关的方法如 " ":meth:`loop.subprocess_exec` 使用。" #: ../../library/asyncio-protocol.rst:116 msgid "" "Interface representing a bidirectional transport, such as a TCP connection." msgstr "接口代表一个双向传输,如 TCP 连接。" #: ../../library/asyncio-protocol.rst:119 msgid "" "The user does not instantiate a transport directly; they call a utility " "function, passing it a protocol factory and other information necessary to " "create the transport and protocol." msgstr "用户不用直接实例化传输;调用一个功能函数,给它传递协议工厂和其它需要的信息就可以创建传输和协议。" #: ../../library/asyncio-protocol.rst:123 msgid "" "Instances of the *Transport* class are returned from or used by event loop " "methods like :meth:`loop.create_connection`, " ":meth:`loop.create_unix_connection`, :meth:`loop.create_server`, " ":meth:`loop.sendfile`, etc." msgstr "" "*Transport* 类实例由如 :meth:`loop.create_connection`、 " ":meth:`loop.create_unix_connection` , :meth:`loop.create_server` , " ":meth:`loop.sendfile` 等这类事件循环方法使用或返回。" #: ../../library/asyncio-protocol.rst:131 msgid "A transport for datagram (UDP) connections." msgstr "数据报 (UDP) 传输连接。" #: ../../library/asyncio-protocol.rst:133 msgid "" "Instances of the *DatagramTransport* class are returned from the " ":meth:`loop.create_datagram_endpoint` event loop method." msgstr "" "*DatagramTransport* 类实例由事件循环方法 :meth:`loop.create_datagram_endpoint` 返回。" #: ../../library/asyncio-protocol.rst:139 msgid "" "An abstraction to represent a connection between a parent and its child OS " "process." msgstr "表示父进程和子进程之间连接的抽象。" #: ../../library/asyncio-protocol.rst:142 msgid "" "Instances of the *SubprocessTransport* class are returned from event loop " "methods :meth:`loop.subprocess_shell` and :meth:`loop.subprocess_exec`." msgstr "" "*SubprocessTransport* 类的实例由事件循环方法 :meth:`loop.subprocess_shell` 和 " ":meth:`loop.subprocess_exec` 返回。" #: ../../library/asyncio-protocol.rst:148 msgid "Base Transport" msgstr "基础传输" #: ../../library/asyncio-protocol.rst:152 msgid "Close the transport." msgstr "关闭传输。" #: ../../library/asyncio-protocol.rst:154 msgid "" "If the transport has a buffer for outgoing data, buffered data will be " "flushed asynchronously. No more data will be received. After all buffered " "data is flushed, the protocol's :meth:`protocol.connection_lost() " "` method will be called with :const:`None` as " "its argument. The transport should not be used once it is closed." msgstr "" "如果传输具有外发数据缓冲区,已缓存的数据将被异步地发送。之后将不会再接收更多数据。在所有已缓存的数据被发送之后,协议的 " ":meth:`protocol.connection_lost() ` 方法将被调用并以 " ":const:`None` 作为其参数。在传输关闭后它就不应再被使用。" #: ../../library/asyncio-protocol.rst:164 msgid "Return ``True`` if the transport is closing or is closed." msgstr "返回 ``True``,如果传输正在关闭或已经关闭。" #: ../../library/asyncio-protocol.rst:168 msgid "" "Return information about the transport or underlying resources it uses." msgstr "返回传输或它使用的底层资源信息。" #: ../../library/asyncio-protocol.rst:171 msgid "" "*name* is a string representing the piece of transport-specific information " "to get." msgstr "*name* 是表示要获取传输特定信息的字符串。" #: ../../library/asyncio-protocol.rst:174 msgid "" "*default* is the value to return if the information is not available, or if " "the transport does not support querying it with the given third-party event " "loop implementation or on the current platform." msgstr "*default* 是在信息不可用或传输不支持第三方事件循环实现或当前平台查询时返回的值。" #: ../../library/asyncio-protocol.rst:179 msgid "" "For example, the following code attempts to get the underlying socket object" " of the transport::" msgstr "例如下面代码尝试获取传输相关套接字对象::" #: ../../library/asyncio-protocol.rst:182 msgid "" "sock = transport.get_extra_info('socket')\n" "if sock is not None:\n" " print(sock.getsockopt(...))" msgstr "" "sock = transport.get_extra_info('socket')\n" "if sock is not None:\n" " print(sock.getsockopt(...))" #: ../../library/asyncio-protocol.rst:186 msgid "Categories of information that can be queried on some transports:" msgstr "传输可查询信息类别:" #: ../../library/asyncio-protocol.rst:188 msgid "socket:" msgstr "套接字:" #: ../../library/asyncio-protocol.rst:190 msgid "" "``'peername'``: the remote address to which the socket is connected, result " "of :meth:`socket.socket.getpeername` (``None`` on error)" msgstr "" "``'peername'``: 套接字连接时的远端地址,:meth:`socket.socket.getpeername` 方法的结果 (出错时为 " "``None`` )" #: ../../library/asyncio-protocol.rst:194 msgid "``'socket'``: :class:`socket.socket` instance" msgstr "``'socket'``: :class:`socket.socket` 实例" #: ../../library/asyncio-protocol.rst:196 msgid "" "``'sockname'``: the socket's own address, result of " ":meth:`socket.socket.getsockname`" msgstr "``'sockname'``: 套接字本地地址, :meth:`socket.socket.getsockname` 方法的结果" #: ../../library/asyncio-protocol.rst:199 msgid "SSL socket:" msgstr "SSL 套接字:" #: ../../library/asyncio-protocol.rst:201 msgid "" "``'compression'``: the compression algorithm being used as a string, or " "``None`` if the connection isn't compressed; result of " ":meth:`ssl.SSLSocket.compression`" msgstr "" "``'compression'``: 用字符串指定压缩算法,或者连接没有压缩时为 ``None`` " ";:meth:`ssl.SSLSocket.compression` 的结果。" #: ../../library/asyncio-protocol.rst:205 msgid "" "``'cipher'``: a three-value tuple containing the name of the cipher being " "used, the version of the SSL protocol that defines its use, and the number " "of secret bits being used; result of :meth:`ssl.SSLSocket.cipher`" msgstr "" "``'cipher'``: 一个三值的元组,包含使用密码的名称,定义使用的 SSL 协议的版本,使用的加密位数。 " ":meth:`ssl.SSLSocket.cipher` 的结果。" #: ../../library/asyncio-protocol.rst:210 msgid "" "``'peercert'``: peer certificate; result of " ":meth:`ssl.SSLSocket.getpeercert`" msgstr "``'peercert'``: 远端凭证; :meth:`ssl.SSLSocket.getpeercert` 结果。" #: ../../library/asyncio-protocol.rst:213 msgid "``'sslcontext'``: :class:`ssl.SSLContext` instance" msgstr "``'sslcontext'``: :class:`ssl.SSLContext` 实例" #: ../../library/asyncio-protocol.rst:215 msgid "" "``'ssl_object'``: :class:`ssl.SSLObject` or :class:`ssl.SSLSocket` instance" msgstr "``'ssl_object'``: :class:`ssl.SSLObject` 或 :class:`ssl.SSLSocket` 实例" #: ../../library/asyncio-protocol.rst:218 msgid "pipe:" msgstr "管道:" #: ../../library/asyncio-protocol.rst:220 msgid "``'pipe'``: pipe object" msgstr "``'pipe'``: 管道对象" #: ../../library/asyncio-protocol.rst:222 msgid "subprocess:" msgstr "子进程:" #: ../../library/asyncio-protocol.rst:224 msgid "``'subprocess'``: :class:`subprocess.Popen` instance" msgstr "``'subprocess'``: :class:`subprocess.Popen` 实例" #: ../../library/asyncio-protocol.rst:228 msgid "Set a new protocol." msgstr "设置一个新协议。" #: ../../library/asyncio-protocol.rst:230 msgid "" "Switching protocol should only be done when both protocols are documented to" " support the switch." msgstr "只有两种协议都写明支持切换才能完成切换协议。" #: ../../library/asyncio-protocol.rst:235 msgid "Return the current protocol." msgstr "返回当前协议。" #: ../../library/asyncio-protocol.rst:239 msgid "Read-only Transports" msgstr "只读传输" #: ../../library/asyncio-protocol.rst:243 msgid "Return ``True`` if the transport is receiving new data." msgstr "如果传输正在接收新数据则返回 ``True``。" #: ../../library/asyncio-protocol.rst:249 msgid "" "Pause the receiving end of the transport. No data will be passed to the " "protocol's :meth:`protocol.data_received() ` method " "until :meth:`resume_reading` is called." msgstr "" "暂停传输的接收端。:meth:`protocol.data_received() ` " "方法将不会收到数据,除非 :meth:`resume_reading`  被调用。" #: ../../library/asyncio-protocol.rst:253 msgid "" "The method is idempotent, i.e. it can be called when the transport is " "already paused or closed." msgstr "这个方法是幂等的,即它可以在传输已经暂停或关闭时调用。" #: ../../library/asyncio-protocol.rst:259 msgid "" "Resume the receiving end. The protocol's :meth:`protocol.data_received() " "` method will be called once again if some data is " "available for reading." msgstr "" "恢复接收端。如果有数据可读取时,协议方法 :meth:`protocol.data_received() " "` 将再次被调用。" #: ../../library/asyncio-protocol.rst:263 msgid "" "The method is idempotent, i.e. it can be called when the transport is " "already reading." msgstr "这个方法是幂等的,即它可以在传输已经准备好读取数据时调用。" #: ../../library/asyncio-protocol.rst:269 msgid "Write-only Transports" msgstr "只写传输" #: ../../library/asyncio-protocol.rst:273 msgid "" "Close the transport immediately, without waiting for pending operations to " "complete. Buffered data will be lost. No more data will be received. The " "protocol's :meth:`protocol.connection_lost() `" " method will eventually be called with :const:`None` as its argument." msgstr "" "立即关闭传输,不会等待已提交的操作处理完毕。已缓存的数据将会丢失。不会接收更多数据。最终 :const:`None` 将作为协议的 " ":meth:`protocol.connection_lost() ` 方法的参数被调用。" #: ../../library/asyncio-protocol.rst:281 msgid "" "Return :const:`True` if the transport supports " ":meth:`~WriteTransport.write_eof`, :const:`False` if not." msgstr "" "如果传输支持 :meth:`~WriteTransport.write_eof` 返回 :const:`True` 否则返回 " ":const:`False`." #: ../../library/asyncio-protocol.rst:286 msgid "Return the current size of the output buffer used by the transport." msgstr "返回传输使用输出缓冲区的当前大小。" #: ../../library/asyncio-protocol.rst:290 msgid "" "Get the *high* and *low* watermarks for write flow control. Return a tuple " "``(low, high)`` where *low* and *high* are positive number of bytes." msgstr "" "获取写入流控制 *high* 和 *low* 高低标记位。返回元组 ``(low, high)``, *low* 和 *high* 为正字节数。" #: ../../library/asyncio-protocol.rst:294 msgid "Use :meth:`set_write_buffer_limits` to set the limits." msgstr "使用 :meth:`set_write_buffer_limits` 设置限制。" #: ../../library/asyncio-protocol.rst:300 msgid "Set the *high* and *low* watermarks for write flow control." msgstr "设置写入流控制 *high* 和 *low* 高低标记位。" #: ../../library/asyncio-protocol.rst:302 msgid "" "These two values (measured in number of bytes) control when the protocol's " ":meth:`protocol.pause_writing() ` and " ":meth:`protocol.resume_writing() ` methods are " "called. If specified, the low watermark must be less than or equal to the " "high watermark. Neither *high* nor *low* can be negative." msgstr "" "这两个值(以字节数表示)控制何时调用协议的 :meth:`protocol.pause_writing() " "` 和 :meth:`protocol.resume_writing() " "` 方法。如果指明,则低水位必须小于或等于高水位。 *high* 和 *low* " "都不能为负值。" #: ../../library/asyncio-protocol.rst:310 msgid "" ":meth:`~BaseProtocol.pause_writing` is called when the buffer size becomes " "greater than or equal to the *high* value. If writing has been paused, " ":meth:`~BaseProtocol.resume_writing` is called when the buffer size becomes " "less than or equal to the *low* value." msgstr "" ":meth:`~BaseProtocol.pause_writing` 会在缓冲区尺寸大于或等于 *high* 值时被调用。 " "如果写入已经被暂停,:meth:`~BaseProtocol.resume_writing` 会在缓冲区尺寸小于或等于 *low* 值时被调用。" #: ../../library/asyncio-protocol.rst:315 msgid "" "The defaults are implementation-specific. If only the high watermark is " "given, the low watermark defaults to an implementation-specific value less " "than or equal to the high watermark. Setting *high* to zero forces *low* to" " zero as well, and causes :meth:`~BaseProtocol.pause_writing` to be called " "whenever the buffer becomes non-empty. Setting *low* to zero causes " ":meth:`~BaseProtocol.resume_writing` to be called only once the buffer is " "empty. Use of zero for either limit is generally sub-optimal as it reduces " "opportunities for doing I/O and computation concurrently." msgstr "" "默认值是实现专属的。如果只给出了高水位值,则低水位值默认为一个小于或等于高水位值的实现专属值。将 *high* 设为零会强制将 *low* " "也设为零,并使得 :meth:`~BaseProtocol.pause_writing` 在缓冲区变为非空的任何时刻被调用。将 *low* 设为零会使得" " :meth:`~BaseProtocol.resume_writing` 在缓冲区为空时只被调用一次。 " "对于上下限都使用零值通常是不够优化的,因为它减少了并发执行 I/O 和计算的机会。" #: ../../library/asyncio-protocol.rst:326 msgid "Use :meth:`~WriteTransport.get_write_buffer_limits` to get the limits." msgstr "可使用 :meth:`~WriteTransport.get_write_buffer_limits` 来获取上下限值。" #: ../../library/asyncio-protocol.rst:331 msgid "Write some *data* bytes to the transport." msgstr "将一些 *data* 字节串写入传输。" #: ../../library/asyncio-protocol.rst:333 #: ../../library/asyncio-protocol.rst:362 msgid "" "This method does not block; it buffers the data and arranges for it to be " "sent out asynchronously." msgstr "此方法不会阻塞;它会缓冲数据并安排其被异步地发出。" #: ../../library/asyncio-protocol.rst:338 msgid "" "Write a list (or any iterable) of data bytes to the transport. This is " "functionally equivalent to calling :meth:`write` on each element yielded by " "the iterable, but may be implemented more efficiently." msgstr "" "将数据字节串的列表(或任意可迭代对象)写入传输。这在功能上等价于在可迭代对象产生的每个元素上调用 :meth:`write`,但其实现可能更为高效。" #: ../../library/asyncio-protocol.rst:345 msgid "" "Close the write end of the transport after flushing all buffered data. Data " "may still be received." msgstr "在刷新所有已缓冲数据之后关闭传输的写入端。数据仍可以被接收。" #: ../../library/asyncio-protocol.rst:348 msgid "" "This method can raise :exc:`NotImplementedError` if the transport (e.g. SSL)" " doesn't support half-closed connections." msgstr "如果传输(例如 SSL)不支持半关闭的连接,此方法会引发 :exc:`NotImplementedError`。" #: ../../library/asyncio-protocol.rst:353 msgid "Datagram Transports" msgstr "数据报传输" #: ../../library/asyncio-protocol.rst:357 msgid "" "Send the *data* bytes to the remote peer given by *addr* (a transport-" "dependent target address). If *addr* is :const:`None`, the data is sent to " "the target address given on transport creation." msgstr "" "将 *data* 字节串发送到 *addr* (基于传输的目标地址) 所给定的远端对等方。如果 *addr* 为 " ":const:`None`,则将数据发送到传输创建时给定的目标地址。" #: ../../library/asyncio-protocol.rst:365 msgid "" "This method can be called with an empty bytes object to send a zero-length " "datagram. The buffer size calculation used for flow control is also updated " "to account for the datagram header." msgstr "调用此方法时可以传入一个空字节串对象来发送零长度的数据报。用于流量控制的缓冲区大小计算也会被更新以计入数据报的标头。" #: ../../library/asyncio-protocol.rst:372 msgid "" "Close the transport immediately, without waiting for pending operations to " "complete. Buffered data will be lost. No more data will be received. The " "protocol's :meth:`protocol.connection_lost() `" " method will eventually be called with :const:`None` as its argument." msgstr "" "立即关闭传输,不会等待已提交的操作执行完毕。已缓存的数据将会丢失。不会接收更多的数据。协议的 " ":meth:`protocol.connection_lost() ` 方法最终将附带 " ":const:`None` 作为参数被调用。" #: ../../library/asyncio-protocol.rst:382 msgid "Subprocess Transports" msgstr "子进程传输" #: ../../library/asyncio-protocol.rst:386 msgid "Return the subprocess process id as an integer." msgstr "将子进程的进程 ID 以整数形式返回。" #: ../../library/asyncio-protocol.rst:390 msgid "" "Return the transport for the communication pipe corresponding to the integer" " file descriptor *fd*:" msgstr "返回对应于整数文件描述符 *fd* 的通信管道的传输:" #: ../../library/asyncio-protocol.rst:393 msgid "" "``0``: writable streaming transport of the standard input (*stdin*), or " ":const:`None` if the subprocess was not created with ``stdin=PIPE``" msgstr "" "``0``: 标准输入 (*stdin*) 的可写流式传输,或者如果子进程创建时未设置 ``stdin=PIPE`` 则为 :const:`None`" #: ../../library/asyncio-protocol.rst:395 msgid "" "``1``: readable streaming transport of the standard output (*stdout*), or " ":const:`None` if the subprocess was not created with ``stdout=PIPE``" msgstr "" "``1``: 标准输出 (*stdout*) 的可读流式传输,或者如果子进程创建时未设置 ``stdout=PIPE`` 则为 " ":const:`None`" #: ../../library/asyncio-protocol.rst:397 msgid "" "``2``: readable streaming transport of the standard error (*stderr*), or " ":const:`None` if the subprocess was not created with ``stderr=PIPE``" msgstr "" "``2``: 标准错误 (*stderr*) 的可读流式传输,或者如果子进程创建时未设置 ``stderr=PIPE`` 则为 " ":const:`None`" #: ../../library/asyncio-protocol.rst:399 msgid "other *fd*: :const:`None`" msgstr "其他 *fd*: :const:`None`" #: ../../library/asyncio-protocol.rst:403 msgid "" "Return the subprocess return code as an integer or :const:`None` if it " "hasn't returned, which is similar to the :attr:`subprocess.Popen.returncode`" " attribute." msgstr "" "返回整数形式的进程返回码,或者如果还未返回则为 :const:`None`,这类似于 " ":attr:`subprocess.Popen.returncode` 属性。" #: ../../library/asyncio-protocol.rst:409 msgid "Kill the subprocess." msgstr "杀死子进程。" #: ../../library/asyncio-protocol.rst:411 msgid "" "On POSIX systems, the function sends SIGKILL to the subprocess. On Windows, " "this method is an alias for :meth:`terminate`." msgstr "" "在 POSIX 系统中,函数会发送 SIGKILL 到子进程。在 Windows 中,此方法是 :meth:`terminate` 的别名。" #: ../../library/asyncio-protocol.rst:414 msgid "See also :meth:`subprocess.Popen.kill`." msgstr "另请参见 :meth:`subprocess.Popen.kill`。" #: ../../library/asyncio-protocol.rst:418 msgid "" "Send the *signal* number to the subprocess, as in " ":meth:`subprocess.Popen.send_signal`." msgstr "发送 *signal* 编号到子进程,与 :meth:`subprocess.Popen.send_signal` 一样。" #: ../../library/asyncio-protocol.rst:423 msgid "Stop the subprocess." msgstr "停止子进程。" #: ../../library/asyncio-protocol.rst:425 msgid "" "On POSIX systems, this method sends :py:const:`~signal.SIGTERM` to the " "subprocess. On Windows, the Windows API function :c:func:`!TerminateProcess`" " is called to stop the subprocess." msgstr "" "在 POSIX 系统中,此方法会发送 :py:const:`~signal.SIGTERM` 到子进程。在 Windows 中,则会调用 Windows" " API 函数 :c:func:`!TerminateProcess` 来停止子进程。" #: ../../library/asyncio-protocol.rst:429 msgid "See also :meth:`subprocess.Popen.terminate`." msgstr "另请参见 :meth:`subprocess.Popen.terminate`。" #: ../../library/asyncio-protocol.rst:433 msgid "Kill the subprocess by calling the :meth:`kill` method." msgstr "通过调用 :meth:`kill` 方法来杀死子进程。" #: ../../library/asyncio-protocol.rst:435 msgid "" "If the subprocess hasn't returned yet, and close transports of *stdin*, " "*stdout*, and *stderr* pipes." msgstr "如果子进程尚未返回,并关闭 *stdin*, *stdout* 和 *stderr* 管道的传输。" #: ../../library/asyncio-protocol.rst:442 msgid "Protocols" msgstr "协议" #: ../../library/asyncio-protocol.rst:444 msgid "**Source code:** :source:`Lib/asyncio/protocols.py`" msgstr "**源码:** :source:`Lib/asyncio/protocols.py`" #: ../../library/asyncio-protocol.rst:448 msgid "" "asyncio provides a set of abstract base classes that should be used to " "implement network protocols. Those classes are meant to be used together " "with :ref:`transports `." msgstr "" "asyncio 提供了一组抽象基类,它们应当被用于实现网络协议。这些类被设计为与 :ref:`传输 ` 配合使用。" #: ../../library/asyncio-protocol.rst:452 msgid "" "Subclasses of abstract base protocol classes may implement some or all " "methods. All these methods are callbacks: they are called by transports on " "certain events, for example when some data is received. A base protocol " "method should be called by the corresponding transport." msgstr "" "抽象基础协议类的子类可以实现其中的部分或全部方法。所有这些方法都是回调:它们由传输在特定事件时调用,例如当数据被接收的时候。 " "基础协议方法应当由相应的传输来调用。" #: ../../library/asyncio-protocol.rst:459 msgid "Base Protocols" msgstr "基础协议" #: ../../library/asyncio-protocol.rst:463 msgid "Base protocol with methods that all protocols share." msgstr "带有所有协议的共享方法的基础协议。" #: ../../library/asyncio-protocol.rst:467 msgid "" "The base class for implementing streaming protocols (TCP, Unix sockets, " "etc)." msgstr "用于实现流式协议(TCP, Unix 套接字等等)的基类。" #: ../../library/asyncio-protocol.rst:472 msgid "" "A base class for implementing streaming protocols with manual control of the" " receive buffer." msgstr "用于实现可对接收缓冲区进行手动控制的流式协议的基类。" #: ../../library/asyncio-protocol.rst:477 msgid "The base class for implementing datagram (UDP) protocols." msgstr "用于实现数据报(UDP)协议的基类。" #: ../../library/asyncio-protocol.rst:481 msgid "" "The base class for implementing protocols communicating with child processes" " (unidirectional pipes)." msgstr "用于实现与子进程通信(单向管道)的协议的基类。" #: ../../library/asyncio-protocol.rst:486 msgid "Base Protocol" msgstr "基础协议" #: ../../library/asyncio-protocol.rst:488 msgid "All asyncio protocols can implement Base Protocol callbacks." msgstr "所有 asyncio 协议均可实现基础协议回调。" #: ../../library/asyncio-protocol.rst:491 msgid "Connection Callbacks" msgstr "连接回调" #: ../../library/asyncio-protocol.rst:492 msgid "" "Connection callbacks are called on all protocols, exactly once per a " "successful connection. All other protocol callbacks can only be called " "between those two methods." msgstr "连接回调会在所有协议上被调用,每个成功的连接将恰好调用一次。所有其他协议回调只能在以下两个方法之间被调用。" #: ../../library/asyncio-protocol.rst:498 msgid "Called when a connection is made." msgstr "连接建立时被调用。" #: ../../library/asyncio-protocol.rst:500 msgid "" "The *transport* argument is the transport representing the connection. The " "protocol is responsible for storing the reference to its transport." msgstr "*transport* 参数是代表连接的传输。此协议负责将引用保存至对应的传输。" #: ../../library/asyncio-protocol.rst:506 msgid "Called when the connection is lost or closed." msgstr "连接丢失或关闭时将被调用。" #: ../../library/asyncio-protocol.rst:508 msgid "" "The argument is either an exception object or :const:`None`. The latter " "means a regular EOF is received, or the connection was aborted or closed by " "this side of the connection." msgstr "方法的参数是一个异常对象或为 :const:`None`。后者意味着收到了常规的 EOF,或者连接被连接的一端取消或关闭。" #: ../../library/asyncio-protocol.rst:514 msgid "Flow Control Callbacks" msgstr "流控制回调" #: ../../library/asyncio-protocol.rst:515 msgid "" "Flow control callbacks can be called by transports to pause or resume " "writing performed by the protocol." msgstr "流控制回调可由传输来调用以暂停或恢复协议所执行的写入操作。" #: ../../library/asyncio-protocol.rst:518 msgid "" "See the documentation of the :meth:`~WriteTransport.set_write_buffer_limits`" " method for more details." msgstr "请查看 :meth:`~WriteTransport.set_write_buffer_limits` 方法的文档了解详情。" #: ../../library/asyncio-protocol.rst:523 msgid "Called when the transport's buffer goes over the high watermark." msgstr "当传输的缓冲区升至高水位以上时将被调用。" #: ../../library/asyncio-protocol.rst:527 msgid "Called when the transport's buffer drains below the low watermark." msgstr "当传输的缓冲区降到低水位以下时将被调用。" #: ../../library/asyncio-protocol.rst:529 msgid "" "If the buffer size equals the high watermark, " ":meth:`~BaseProtocol.pause_writing` is not called: the buffer size must go " "strictly over." msgstr "" "如果缓冲区大小等于高水位值,则 :meth:`~BaseProtocol.pause_writing` 不会被调用:缓冲区大小必须要高于该值。" #: ../../library/asyncio-protocol.rst:533 msgid "" "Conversely, :meth:`~BaseProtocol.resume_writing` is called when the buffer " "size is equal or lower than the low watermark. These end conditions are " "important to ensure that things go as expected when either mark is zero." msgstr "" "相反地,:meth:`~BaseProtocol.resume_writing` 会在缓冲区大小等于或小于低水位值时被调用。 " "这些结束条件对于当两个水位取零值时也能确保符合预期的行为是很重要的。" #: ../../library/asyncio-protocol.rst:540 msgid "Streaming Protocols" msgstr "流式协议" #: ../../library/asyncio-protocol.rst:542 msgid "" "Event methods, such as :meth:`loop.create_server`, " ":meth:`loop.create_unix_server`, :meth:`loop.create_connection`, " ":meth:`loop.create_unix_connection`, :meth:`loop.connect_accepted_socket`, " ":meth:`loop.connect_read_pipe`, and :meth:`loop.connect_write_pipe` accept " "factories that return streaming protocols." msgstr "" "事件方法,例如 :meth:`loop.create_server`, :meth:`loop.create_unix_server`, " ":meth:`loop.create_connection`, :meth:`loop.create_unix_connection`, " ":meth:`loop.connect_accepted_socket`, :meth:`loop.connect_read_pipe` 和 " ":meth:`loop.connect_write_pipe` 都接受返回流式协议的工厂。" #: ../../library/asyncio-protocol.rst:550 msgid "" "Called when some data is received. *data* is a non-empty bytes object " "containing the incoming data." msgstr "当收到数据时被调用。 *data* 为包含入站数据的非空字节串对象。" #: ../../library/asyncio-protocol.rst:553 msgid "" "Whether the data is buffered, chunked or reassembled depends on the " "transport. In general, you shouldn't rely on specific semantics and instead" " make your parsing generic and flexible. However, data is always received in" " the correct order." msgstr "" "数据是否会被缓冲、分块或重组取决于具体传输。通常,你不应依赖于特定的语义而应使你的解析具有通用性和灵活性。但是,数据总是要以正确的顺序被接收。" #: ../../library/asyncio-protocol.rst:558 msgid "" "The method can be called an arbitrary number of times while a connection is " "open." msgstr "此方法在连接打开期间可以被调用任意次数。" #: ../../library/asyncio-protocol.rst:561 msgid "" "However, :meth:`protocol.eof_received() ` is called " "at most once. Once ``eof_received()`` is called, ``data_received()`` is not" " called anymore." msgstr "" "但是,:meth:`protocol.eof_received() ` 最多只会被调用一次。一旦 " "``eof_received()`` 被调用,``data_received()`` 就不会再被调用。" #: ../../library/asyncio-protocol.rst:567 msgid "" "Called when the other end signals it won't send any more data (for example " "by calling :meth:`transport.write_eof() `, if the " "other end also uses asyncio)." msgstr "" "当另一端发信号表示不会再发送数据时被调用(例如通过调用 :meth:`transport.write_eof() " "`,如果另一端也使用 asyncio 的话)。" #: ../../library/asyncio-protocol.rst:572 msgid "" "This method may return a false value (including ``None``), in which case the" " transport will close itself. Conversely, if this method returns a true " "value, the protocol used determines whether to close the transport. Since " "the default implementation returns ``None``, it implicitly closes the " "connection." msgstr "" "此方法可能返回假值 (包括 ``None``),在此情况下传输将会自行关闭。相反地,如果此方法返回真值,将以所用的协议来确定是否要关闭传输。 " "由于默认实现是返回 ``None``,因此它会隐式地关闭连接。" #: ../../library/asyncio-protocol.rst:578 msgid "" "Some transports, including SSL, don't support half-closed connections, in " "which case returning true from this method will result in the connection " "being closed." msgstr "某些传输,包括 SSL 在内,并不支持半关闭的连接,在此情况下从该方法返回真值将导致连接被关闭。" #: ../../library/asyncio-protocol.rst:583 #: ../../library/asyncio-protocol.rst:641 msgid "State machine:" msgstr "状态机:" #: ../../library/asyncio-protocol.rst:585 msgid "" "start -> connection_made\n" " [-> data_received]*\n" " [-> eof_received]?\n" "-> connection_lost -> end" msgstr "" "start -> connection_made\n" " [-> data_received]*\n" " [-> eof_received]?\n" "-> connection_lost -> end" #: ../../library/asyncio-protocol.rst:594 msgid "Buffered Streaming Protocols" msgstr "缓冲流协议" #: ../../library/asyncio-protocol.rst:598 msgid "" "Buffered Protocols can be used with any event loop method that supports " "`Streaming Protocols`_." msgstr "带缓冲的协议可与任何支持 `Streaming Protocols`_ 的事件循环方法配合使用。" #: ../../library/asyncio-protocol.rst:601 msgid "" "``BufferedProtocol`` implementations allow explicit manual allocation and " "control of the receive buffer. Event loops can then use the buffer provided" " by the protocol to avoid unnecessary data copies. This can result in " "noticeable performance improvement for protocols that receive big amounts of" " data. Sophisticated protocol implementations can significantly reduce the " "number of buffer allocations." msgstr "" "``BufferedProtocol`` 实现允许显式手动分配和控制接收缓冲区。随后事件循环可以使用协议提供的缓冲区来避免不必要的数据复制。 " "这对于接收大量数据的协议来说会有明显的性能提升。复杂的协议实现能显著地减少缓冲区分配的数量。" #: ../../library/asyncio-protocol.rst:608 msgid "" "The following callbacks are called on :class:`BufferedProtocol` instances:" msgstr "以下回调是在 :class:`BufferedProtocol` 实例上被调用的:" #: ../../library/asyncio-protocol.rst:613 msgid "Called to allocate a new receive buffer." msgstr "调用后会分配新的接收缓冲区。" #: ../../library/asyncio-protocol.rst:615 msgid "" "*sizehint* is the recommended minimum size for the returned buffer. It is " "acceptable to return smaller or larger buffers than what *sizehint* " "suggests. When set to -1, the buffer size can be arbitrary. It is an error " "to return a buffer with a zero size." msgstr "" "*sizehint* 是推荐的返回缓冲区最小尺寸。返回小于或大于 *sizehint* 推荐尺寸的缓冲区也是可接受的。当设为 -1 " "时,缓冲区尺寸可以是任意的。返回尺寸为零的缓冲区则是错误的。" #: ../../library/asyncio-protocol.rst:620 msgid "" "``get_buffer()`` must return an object implementing the :ref:`buffer " "protocol `." msgstr "``get_buffer()`` 必须返回一个实现了 :ref:`缓冲区协议 ` 的对象。" #: ../../library/asyncio-protocol.rst:625 msgid "Called when the buffer was updated with the received data." msgstr "用接收的数据更新缓冲区时被调用。" #: ../../library/asyncio-protocol.rst:627 msgid "*nbytes* is the total number of bytes that were written to the buffer." msgstr "*nbytes* 是被写入到缓冲区的字节总数。" #: ../../library/asyncio-protocol.rst:631 msgid "" "See the documentation of the :meth:`protocol.eof_received() " "` method." msgstr "请查看 :meth:`protocol.eof_received() ` 方法的文档。" #: ../../library/asyncio-protocol.rst:635 msgid "" ":meth:`~BufferedProtocol.get_buffer` can be called an arbitrary number of " "times during a connection. However, :meth:`protocol.eof_received() " "` is called at most once and, if called, " ":meth:`~BufferedProtocol.get_buffer` and " ":meth:`~BufferedProtocol.buffer_updated` won't be called after it." msgstr "" "在连接期间 :meth:`~BufferedProtocol.get_buffer` 可以被调用任意次数。 " "但是,:meth:`protocol.eof_received() ` " "最多只能被调用一次,如果被调用,则在此之后 :meth:`~BufferedProtocol.get_buffer` 和 " ":meth:`~BufferedProtocol.buffer_updated` 不能再被调用。" #: ../../library/asyncio-protocol.rst:643 msgid "" "start -> connection_made\n" " [-> get_buffer\n" " [-> buffer_updated]?\n" " ]*\n" " [-> eof_received]?\n" "-> connection_lost -> end" msgstr "" "start -> connection_made\n" " [-> get_buffer\n" " [-> buffer_updated]?\n" " ]*\n" " [-> eof_received]?\n" "-> connection_lost -> end" #: ../../library/asyncio-protocol.rst:654 msgid "Datagram Protocols" msgstr "数据报协议" #: ../../library/asyncio-protocol.rst:656 msgid "" "Datagram Protocol instances should be constructed by protocol factories " "passed to the :meth:`loop.create_datagram_endpoint` method." msgstr "数据报协议实例应当由传递给 :meth:`loop.create_datagram_endpoint` 方法的协议工厂来构造。" #: ../../library/asyncio-protocol.rst:661 msgid "" "Called when a datagram is received. *data* is a bytes object containing the" " incoming data. *addr* is the address of the peer sending the data; the " "exact format depends on the transport." msgstr "当接收到数据报时被调用。 *data* 是包含传入数据的字节串对象。 *addr* 是发送数据的对等端地址;实际的格式取决于具体传输。" #: ../../library/asyncio-protocol.rst:667 msgid "" "Called when a previous send or receive operation raises an :class:`OSError`." " *exc* is the :class:`OSError` instance." msgstr "当前一个发送或接收操作引发 :class:`OSError` 时被调用。 *exc* 是 :class:`OSError` 的实例。" #: ../../library/asyncio-protocol.rst:670 msgid "" "This method is called in rare conditions, when the transport (e.g. UDP) " "detects that a datagram could not be delivered to its recipient. In many " "conditions though, undeliverable datagrams will be silently dropped." msgstr "此方法会在当传输(例如 UDP)检测到无法将数据报传给接收方等极少数情况下被调用。而在大多数情况下,无法送达的数据报将被静默地丢弃。" #: ../../library/asyncio-protocol.rst:677 msgid "" "On BSD systems (macOS, FreeBSD, etc.) flow control is not supported for " "datagram protocols, because there is no reliable way to detect send failures" " caused by writing too many packets." msgstr "在 BSD 系统(macOS, FreeBSD 等等)上,数据报协议不支持流控制,因为没有可靠的方式来检测因写入过多包所导致的发送失败。" #: ../../library/asyncio-protocol.rst:681 msgid "" "The socket always appears 'ready' and excess packets are dropped. An " ":class:`OSError` with ``errno`` set to :const:`errno.ENOBUFS` may or may not" " be raised; if it is raised, it will be reported to " ":meth:`DatagramProtocol.error_received` but otherwise ignored." msgstr "" "套接字总是显示为 'ready' 且多余的包会被丢弃。有一定的可能性会引发 :class:`OSError` 并设置 ``errno`` 为 " ":const:`errno.ENOBUFS`;如果此异常被引发,它将被报告给 " ":meth:`DatagramProtocol.error_received`,在其他情况下则会被忽略。" #: ../../library/asyncio-protocol.rst:690 msgid "Subprocess Protocols" msgstr "子进程协议" #: ../../library/asyncio-protocol.rst:692 msgid "" "Subprocess Protocol instances should be constructed by protocol factories " "passed to the :meth:`loop.subprocess_exec` and :meth:`loop.subprocess_shell`" " methods." msgstr "" "子进程协议实例应当由传递给 :meth:`loop.subprocess_exec` 和 :meth:`loop.subprocess_shell` " "方法的协议工厂函数来构造。" #: ../../library/asyncio-protocol.rst:698 msgid "" "Called when the child process writes data into its stdout or stderr pipe." msgstr "当子进程向其 stdout 或 stderr 管道写入数据时被调用。" #: ../../library/asyncio-protocol.rst:701 msgid "*fd* is the integer file descriptor of the pipe." msgstr "*fd* 是以整数表示的管道文件描述符。" #: ../../library/asyncio-protocol.rst:703 msgid "*data* is a non-empty bytes object containing the received data." msgstr "*data* 是包含已接收数据的非空字节串对象。" #: ../../library/asyncio-protocol.rst:707 msgid "" "Called when one of the pipes communicating with the child process is closed." msgstr "与子进程通信的其中一个管道关闭时被调用。" #: ../../library/asyncio-protocol.rst:710 msgid "*fd* is the integer file descriptor that was closed." msgstr "*fd* 是以整数表示的已关闭文件描述符。" #: ../../library/asyncio-protocol.rst:714 msgid "Called when the child process has exited." msgstr "子进程退出时被调用。" #: ../../library/asyncio-protocol.rst:716 msgid "" "It can be called before :meth:`~SubprocessProtocol.pipe_data_received` and " ":meth:`~SubprocessProtocol.pipe_connection_lost` methods." msgstr "" "它可以在 :meth:`~SubprocessProtocol.pipe_data_received` 和 " ":meth:`~SubprocessProtocol.pipe_connection_lost` 方法之前被调用。" #: ../../library/asyncio-protocol.rst:721 msgid "Examples" msgstr "例子" #: ../../library/asyncio-protocol.rst:726 msgid "TCP Echo Server" msgstr "TCP 回显服务器" #: ../../library/asyncio-protocol.rst:728 msgid "" "Create a TCP echo server using the :meth:`loop.create_server` method, send " "back received data, and close the connection::" msgstr "使用 :meth:`loop.create_server` 方法创建 TCP 回显服务器,发回已接收的数据,并关闭连接::" #: ../../library/asyncio-protocol.rst:731 msgid "" "import asyncio\n" "\n" "\n" "class EchoServerProtocol(asyncio.Protocol):\n" " def connection_made(self, transport):\n" " peername = transport.get_extra_info('peername')\n" " print('Connection from {}'.format(peername))\n" " self.transport = transport\n" "\n" " def data_received(self, data):\n" " message = data.decode()\n" " print('Data received: {!r}'.format(message))\n" "\n" " print('Send: {!r}'.format(message))\n" " self.transport.write(data)\n" "\n" " print('Close the client socket')\n" " self.transport.close()\n" "\n" "\n" "async def main():\n" " # Get a reference to the event loop as we plan to use\n" " # low-level APIs.\n" " loop = asyncio.get_running_loop()\n" "\n" " server = await loop.create_server(\n" " EchoServerProtocol,\n" " '127.0.0.1', 8888)\n" "\n" " async with server:\n" " await server.serve_forever()\n" "\n" "\n" "asyncio.run(main())" msgstr "" "import asyncio\n" "\n" "\n" "class EchoServerProtocol(asyncio.Protocol):\n" " def connection_made(self, transport):\n" " peername = transport.get_extra_info('peername')\n" " print('Connection from {}'.format(peername))\n" " self.transport = transport\n" "\n" " def data_received(self, data):\n" " message = data.decode()\n" " print('Data received: {!r}'.format(message))\n" "\n" " print('Send: {!r}'.format(message))\n" " self.transport.write(data)\n" "\n" " print('Close the client socket')\n" " self.transport.close()\n" "\n" "\n" "async def main():\n" " # 获取指向事件循环的引用\n" " # 因为我们准备使用低层级 API。\n" " loop = asyncio.get_running_loop()\n" "\n" " server = await loop.create_server(\n" " EchoServerProtocol,\n" " '127.0.0.1', 8888)\n" "\n" " async with server:\n" " await server.serve_forever()\n" "\n" "\n" "asyncio.run(main())" #: ../../library/asyncio-protocol.rst:769 msgid "" "The :ref:`TCP echo server using streams ` " "example uses the high-level :func:`asyncio.start_server` function." msgstr "" ":ref:`使用流的 TCP 回显服务器 ` 示例,使用了高层级的 " ":func:`asyncio.start_server` 函数。" #: ../../library/asyncio-protocol.rst:775 msgid "TCP Echo Client" msgstr "TCP 回显客户端" #: ../../library/asyncio-protocol.rst:777 msgid "" "A TCP echo client using the :meth:`loop.create_connection` method, sends " "data, and waits until the connection is closed::" msgstr "使用 :meth:`loop.create_connection` 方法的 TCP 回显客户端,发送数据并等待,直到连接被关闭::" #: ../../library/asyncio-protocol.rst:780 msgid "" "import asyncio\n" "\n" "\n" "class EchoClientProtocol(asyncio.Protocol):\n" " def __init__(self, message, on_con_lost):\n" " self.message = message\n" " self.on_con_lost = on_con_lost\n" "\n" " def connection_made(self, transport):\n" " transport.write(self.message.encode())\n" " print('Data sent: {!r}'.format(self.message))\n" "\n" " def data_received(self, data):\n" " print('Data received: {!r}'.format(data.decode()))\n" "\n" " def connection_lost(self, exc):\n" " print('The server closed the connection')\n" " self.on_con_lost.set_result(True)\n" "\n" "\n" "async def main():\n" " # Get a reference to the event loop as we plan to use\n" " # low-level APIs.\n" " loop = asyncio.get_running_loop()\n" "\n" " on_con_lost = loop.create_future()\n" " message = 'Hello World!'\n" "\n" " transport, protocol = await loop.create_connection(\n" " lambda: EchoClientProtocol(message, on_con_lost),\n" " '127.0.0.1', 8888)\n" "\n" " # Wait until the protocol signals that the connection\n" " # is lost and close the transport.\n" " try:\n" " await on_con_lost\n" " finally:\n" " transport.close()\n" "\n" "\n" "asyncio.run(main())" msgstr "" "import asyncio\n" "\n" "\n" "class EchoClientProtocol(asyncio.Protocol):\n" " def __init__(self, message, on_con_lost):\n" " self.message = message\n" " self.on_con_lost = on_con_lost\n" "\n" " def connection_made(self, transport):\n" " transport.write(self.message.encode())\n" " print('Data sent: {!r}'.format(self.message))\n" "\n" " def data_received(self, data):\n" " print('Data received: {!r}'.format(data.decode()))\n" "\n" " def connection_lost(self, exc):\n" " print('The server closed the connection')\n" " self.on_con_lost.set_result(True)\n" "\n" "\n" "async def main():\n" " # 获取指向事件循环的引用\n" " # 因为我们准备使用低层级 API。\n" " loop = asyncio.get_running_loop()\n" "\n" " on_con_lost = loop.create_future()\n" " message = 'Hello World!'\n" "\n" " transport, protocol = await loop.create_connection(\n" " lambda: EchoClientProtocol(message, on_con_lost),\n" " '127.0.0.1', 8888)\n" "\n" " # 等待发出连接丢失的协议信号\n" " # 并关闭传输。\n" " try:\n" " await on_con_lost\n" " finally:\n" " transport.close()\n" "\n" "\n" "asyncio.run(main())" #: ../../library/asyncio-protocol.rst:825 msgid "" "The :ref:`TCP echo client using streams ` " "example uses the high-level :func:`asyncio.open_connection` function." msgstr "" ":ref:`使用流的 TCP 回显客户端 ` 示例,使用了高层级的 " ":func:`asyncio.open_connection` 函数。" #: ../../library/asyncio-protocol.rst:832 msgid "UDP Echo Server" msgstr "UDP 回显服务器" #: ../../library/asyncio-protocol.rst:834 msgid "" "A UDP echo server, using the :meth:`loop.create_datagram_endpoint` method, " "sends back received data::" msgstr "使用 :meth:`loop.create_datagram_endpoint` 方法的 UDP 回显服务器,发回已接收的数据::" #: ../../library/asyncio-protocol.rst:837 msgid "" "import asyncio\n" "\n" "\n" "class EchoServerProtocol:\n" " def connection_made(self, transport):\n" " self.transport = transport\n" "\n" " def datagram_received(self, data, addr):\n" " message = data.decode()\n" " print('Received %r from %s' % (message, addr))\n" " print('Send %r to %s' % (message, addr))\n" " self.transport.sendto(data, addr)\n" "\n" "\n" "async def main():\n" " print(\"Starting UDP server\")\n" "\n" " # Get a reference to the event loop as we plan to use\n" " # low-level APIs.\n" " loop = asyncio.get_running_loop()\n" "\n" " # One protocol instance will be created to serve all\n" " # client requests.\n" " transport, protocol = await loop.create_datagram_endpoint(\n" " EchoServerProtocol,\n" " local_addr=('127.0.0.1', 9999))\n" "\n" " try:\n" " await asyncio.sleep(3600) # Serve for 1 hour.\n" " finally:\n" " transport.close()\n" "\n" "\n" "asyncio.run(main())" msgstr "" "import asyncio\n" "\n" "\n" "class EchoServerProtocol:\n" " def connection_made(self, transport):\n" " self.transport = transport\n" "\n" " def datagram_received(self, data, addr):\n" " message = data.decode()\n" " print('Received %r from %s' % (message, addr))\n" " print('Send %r to %s' % (message, addr))\n" " self.transport.sendto(data, addr)\n" "\n" "\n" "async def main():\n" " print(\"Starting UDP server\")\n" "\n" " # 获取对事件循环的引用\n" " # 因为我们打算使用低层级的 APIs。\n" " loop = asyncio.get_running_loop()\n" "\n" " # 将创建一个协议实例来为所有客户端请求提供服务。\n" " transport, protocol = await loop.create_datagram_endpoint(\n" " EchoServerProtocol,\n" " local_addr=('127.0.0.1', 9999))\n" "\n" " try:\n" " await asyncio.sleep(3600) # 服务持续 1 小时。\n" " finally:\n" " transport.close()\n" "\n" "\n" "asyncio.run(main())" #: ../../library/asyncio-protocol.rst:876 msgid "UDP Echo Client" msgstr "UDP 回显客户端" #: ../../library/asyncio-protocol.rst:878 msgid "" "A UDP echo client, using the :meth:`loop.create_datagram_endpoint` method, " "sends data and closes the transport when it receives the answer::" msgstr "" "使用 :meth:`loop.create_datagram_endpoint` 方法的 UDP 回显客户端,发送数据并在收到回应时关闭传输::" #: ../../library/asyncio-protocol.rst:881 msgid "" "import asyncio\n" "\n" "\n" "class EchoClientProtocol:\n" " def __init__(self, message, on_con_lost):\n" " self.message = message\n" " self.on_con_lost = on_con_lost\n" " self.transport = None\n" "\n" " def connection_made(self, transport):\n" " self.transport = transport\n" " print('Send:', self.message)\n" " self.transport.sendto(self.message.encode())\n" "\n" " def datagram_received(self, data, addr):\n" " print(\"Received:\", data.decode())\n" "\n" " print(\"Close the socket\")\n" " self.transport.close()\n" "\n" " def error_received(self, exc):\n" " print('Error received:', exc)\n" "\n" " def connection_lost(self, exc):\n" " print(\"Connection closed\")\n" " self.on_con_lost.set_result(True)\n" "\n" "\n" "async def main():\n" " # Get a reference to the event loop as we plan to use\n" " # low-level APIs.\n" " loop = asyncio.get_running_loop()\n" "\n" " on_con_lost = loop.create_future()\n" " message = \"Hello World!\"\n" "\n" " transport, protocol = await loop.create_datagram_endpoint(\n" " lambda: EchoClientProtocol(message, on_con_lost),\n" " remote_addr=('127.0.0.1', 9999))\n" "\n" " try:\n" " await on_con_lost\n" " finally:\n" " transport.close()\n" "\n" "\n" "asyncio.run(main())" msgstr "" "import asyncio\n" "\n" "\n" "class EchoClientProtocol:\n" " def __init__(self, message, on_con_lost):\n" " self.message = message\n" " self.on_con_lost = on_con_lost\n" " self.transport = None\n" "\n" " def connection_made(self, transport):\n" " self.transport = transport\n" " print('Send:', self.message)\n" " self.transport.sendto(self.message.encode())\n" "\n" " def datagram_received(self, data, addr):\n" " print(\"Received:\", data.decode())\n" "\n" " print(\"Close the socket\")\n" " self.transport.close()\n" "\n" " def error_received(self, exc):\n" " print('Error received:', exc)\n" "\n" " def connection_lost(self, exc):\n" " print(\"Connection closed\")\n" " self.on_con_lost.set_result(True)\n" "\n" "\n" "async def main():\n" " # 获取一个对事件循环的引用\n" " # 因为我们计划使用低层级的 API。\n" " loop = asyncio.get_running_loop()\n" "\n" " on_con_lost = loop.create_future()\n" " message = \"Hello World!\"\n" "\n" " transport, protocol = await loop.create_datagram_endpoint(\n" " lambda: EchoClientProtocol(message, on_con_lost),\n" " remote_addr=('127.0.0.1', 9999))\n" "\n" " try:\n" " await on_con_lost\n" " finally:\n" " transport.close()\n" "\n" "\n" "asyncio.run(main())" #: ../../library/asyncio-protocol.rst:933 msgid "Connecting Existing Sockets" msgstr "连接已有的套接字" #: ../../library/asyncio-protocol.rst:935 msgid "" "Wait until a socket receives data using the :meth:`loop.create_connection` " "method with a protocol::" msgstr "附带一个协议使用 :meth:`loop.create_connection` 方法,等待直到套接字接收数据::" #: ../../library/asyncio-protocol.rst:938 msgid "" "import asyncio\n" "import socket\n" "\n" "\n" "class MyProtocol(asyncio.Protocol):\n" "\n" " def __init__(self, on_con_lost):\n" " self.transport = None\n" " self.on_con_lost = on_con_lost\n" "\n" " def connection_made(self, transport):\n" " self.transport = transport\n" "\n" " def data_received(self, data):\n" " print(\"Received:\", data.decode())\n" "\n" " # We are done: close the transport;\n" " # connection_lost() will be called automatically.\n" " self.transport.close()\n" "\n" " def connection_lost(self, exc):\n" " # The socket has been closed\n" " self.on_con_lost.set_result(True)\n" "\n" "\n" "async def main():\n" " # Get a reference to the event loop as we plan to use\n" " # low-level APIs.\n" " loop = asyncio.get_running_loop()\n" " on_con_lost = loop.create_future()\n" "\n" " # Create a pair of connected sockets\n" " rsock, wsock = socket.socketpair()\n" "\n" " # Register the socket to wait for data.\n" " transport, protocol = await loop.create_connection(\n" " lambda: MyProtocol(on_con_lost), sock=rsock)\n" "\n" " # Simulate the reception of data from the network.\n" " loop.call_soon(wsock.send, 'abc'.encode())\n" "\n" " try:\n" " await protocol.on_con_lost\n" " finally:\n" " transport.close()\n" " wsock.close()\n" "\n" "asyncio.run(main())" msgstr "" "import asyncio\n" "import socket\n" "\n" "\n" "class MyProtocol(asyncio.Protocol):\n" "\n" " def __init__(self, on_con_lost):\n" " self.transport = None\n" " self.on_con_lost = on_con_lost\n" "\n" " def connection_made(self, transport):\n" " self.transport = transport\n" "\n" " def data_received(self, data):\n" " print(\"Received:\", data.decode())\n" "\n" " # 已完成:关闭传输;\n" " # connection_lost() 将自动被调用。\n" " self.transport.close()\n" "\n" " def connection_lost(self, exc):\n" " # 套接字已被关闭\n" " self.on_con_lost.set_result(True)\n" "\n" "\n" "async def main():\n" " # 获取指向事件循环的引用\n" " # 因为我们准备使用低层级 API。\n" " loop = asyncio.get_running_loop()\n" " on_con_lost = loop.create_future()\n" "\n" " # 创建一对已连接的套接字\n" " rsock, wsock = socket.socketpair()\n" "\n" " # 注册套接字以等待数据。\n" " transport, protocol = await loop.create_connection(\n" " lambda: MyProtocol(on_con_lost), sock=rsock)\n" "\n" " # 模拟从网络接收数据。\n" " loop.call_soon(wsock.send, 'abc'.encode())\n" "\n" " try:\n" " await protocol.on_con_lost\n" " finally:\n" " transport.close()\n" " wsock.close()\n" "\n" "asyncio.run(main())" #: ../../library/asyncio-protocol.rst:989 msgid "" "The :ref:`watch a file descriptor for read events " "` example uses the low-level " ":meth:`loop.add_reader` method to register an FD." msgstr "" "使用低层级的 :meth:`loop.add_reader` 方法来注册一个 FD 的 :ref:`监视文件描述符以读取事件 " "` 示例。" #: ../../library/asyncio-protocol.rst:993 msgid "" "The :ref:`register an open socket to wait for data using streams " "` example uses high-level streams" " created by the :func:`open_connection` function in a coroutine." msgstr "" "使用在协程中通过 :func:`open_connection` 函数创建的高层级流的 :ref:`注册一个打开的套接字以等待使用流的数据 " "` 示例。" #: ../../library/asyncio-protocol.rst:1000 msgid "loop.subprocess_exec() and SubprocessProtocol" msgstr "loop.subprocess_exec() 与 SubprocessProtocol" #: ../../library/asyncio-protocol.rst:1002 msgid "" "An example of a subprocess protocol used to get the output of a subprocess " "and to wait for the subprocess exit." msgstr "一个使用子进程协议来获取子进程的输出并等待子进程退出的示例。" #: ../../library/asyncio-protocol.rst:1005 msgid "The subprocess is created by the :meth:`loop.subprocess_exec` method::" msgstr "这个子进程是由 :meth:`loop.subprocess_exec` 方法创建的::" #: ../../library/asyncio-protocol.rst:1007 msgid "" "import asyncio\n" "import sys\n" "\n" "class DateProtocol(asyncio.SubprocessProtocol):\n" " def __init__(self, exit_future):\n" " self.exit_future = exit_future\n" " self.output = bytearray()\n" " self.pipe_closed = False\n" " self.exited = False\n" "\n" " def pipe_connection_lost(self, fd, exc):\n" " self.pipe_closed = True\n" " self.check_for_exit()\n" "\n" " def pipe_data_received(self, fd, data):\n" " self.output.extend(data)\n" "\n" " def process_exited(self):\n" " self.exited = True\n" " # process_exited() method can be called before\n" " # pipe_connection_lost() method: wait until both methods are\n" " # called.\n" " self.check_for_exit()\n" "\n" " def check_for_exit(self):\n" " if self.pipe_closed and self.exited:\n" " self.exit_future.set_result(True)\n" "\n" "async def get_date():\n" " # Get a reference to the event loop as we plan to use\n" " # low-level APIs.\n" " loop = asyncio.get_running_loop()\n" "\n" " code = 'import datetime as dt; print(dt.datetime.now())'\n" " exit_future = asyncio.Future(loop=loop)\n" "\n" " # Create the subprocess controlled by DateProtocol;\n" " # redirect the standard output into a pipe.\n" " transport, protocol = await loop.subprocess_exec(\n" " lambda: DateProtocol(exit_future),\n" " sys.executable, '-c', code,\n" " stdin=None, stderr=None)\n" "\n" " # Wait for the subprocess exit using the process_exited()\n" " # method of the protocol.\n" " await exit_future\n" "\n" " # Close the stdout pipe.\n" " transport.close()\n" "\n" " # Read the output which was collected by the\n" " # pipe_data_received() method of the protocol.\n" " data = bytes(protocol.output)\n" " return data.decode('ascii').rstrip()\n" "\n" "date = asyncio.run(get_date())\n" "print(f\"Current date: {date}\")" msgstr "" "import asyncio\n" "import sys\n" "\n" "class DateProtocol(asyncio.SubprocessProtocol):\n" " def __init__(self, exit_future):\n" " self.exit_future = exit_future\n" " self.output = bytearray()\n" " self.pipe_closed = False\n" " self.exited = False\n" "\n" " def pipe_connection_lost(self, fd, exc):\n" " self.pipe_closed = True\n" " self.check_for_exit()\n" "\n" " def pipe_data_received(self, fd, data):\n" " self.output.extend(data)\n" "\n" " def process_exited(self):\n" " self.exited = True\n" " # process_exited() 方法可以在\n" " # pipe_connection_lost() 方法之前被调用:\n" " # 等待直到两个方法都已被调用。\n" " self.check_for_exit()\n" "\n" " def check_for_exit(self):\n" " if self.pipe_closed and self.exited:\n" " self.exit_future.set_result(True)\n" "\n" "async def get_date():\n" " # 获取对事件循环的引用因为我们打算使用\n" " # 低层级 API。\n" " loop = asyncio.get_running_loop()\n" "\n" " code = 'import datetime as dt; print(dt.datetime.now())'\n" " exit_future = asyncio.Future(loop=loop)\n" "\n" " # 创建由 DateProtocol 控制的子进程;\n" " # 重定向标准输出到一个管道。\n" " transport, protocol = await loop.subprocess_exec(\n" " lambda: DateProtocol(exit_future),\n" " sys.executable, '-c', code,\n" " stdin=None, stderr=None)\n" "\n" " # 使用协议的 process_exited() 方法\n" " # 等待子进程退出。\n" " await exit_future\n" "\n" " # 关闭 stdout 管道。\n" " transport.close()\n" "\n" " # 读取由协议的 pipe_data_received() 方法\n" " # 所收集的输出。\n" " data = bytes(protocol.output)\n" " return data.decode('ascii').rstrip()\n" "\n" "date = asyncio.run(get_date())\n" "print(f\"Current date: {date}\")" #: ../../library/asyncio-protocol.rst:1065 msgid "" "See also the :ref:`same example ` " "written using high-level APIs." msgstr "" "另请参阅使用高层级 API 编写的 :ref:`相同示例 `。"