Python类库中文翻译:Socket 对象(只翻译了一点)

17.2.1 Socket Objects

Socket objects have the following methods. Except for makefile() these correspond to Unix system calls applicable to sockets.

accept( )
Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.

bind( address)
Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family — see above.) Note: This method has historically accepted a pair of parameters for AF_INET addresses instead of only a tuple. This was never intentional and is no longer available in Python 2.0 and later.

close( )
Close the socket. All future operations on the socket object will fail. The remote end will receive no more data (after queued data is flushed). Sockets are automatically closed when they are garbage-collected.

connect( address)
Connect to a remote socket at address. (The format of address depends on the address family — see above.) Note: This method has historically accepted a pair of parameters for AF_INET addresses instead of only a tuple. This was never intentional and is no longer available in Python 2.0 and later.

connect_ex( address)
Like connect(address), but return an error indicator instead of raising an exception for errors returned by the C-level connect() call (other problems, such as “host not found,” can still raise exceptions). The error indicator is 0 if the operation succeeded, otherwise the value of the errno variable. This is useful to support, for example, asynchronous connects. Note: This method has historically accepted a pair of parameters for AF_INET addresses instead of only a tuple. This was never intentional and is no longer available in Python 2.0 and later.

fileno( )
Return the socket’s file descriptor (a small integer). This is useful with select.select().
返回这个套接字的文件描述符(一个 small integer)。它用于 select.select()

Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as os.fdopen()). Unix does not have this limitation.
在 Windows 本方法返回的small integer 不能当作一个文件描述符使用(例如 os.fdopen())。 Unix 没有此限制。

getpeername( )
Return the remote address to which the socket is connected. This is useful to find out the port number of a remote IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.) On some systems this function is not supported.

getsockname( )
Return the socket’s own address. This is useful to find out the port number of an IPv4/v6 socket, for instance. (The format of the address returned depends on the address family — see above.)

getsockopt( level, optname[, buflen])
Return the value of the given socket option (see the Unix man page getsockopt(2)). The needed symbolic constants (SO_* etc.) are defined in this module. If buflen is absent, an integer option is assumed and its integer value is returned by the function. If buflen is present, it specifies the maximum length of the buffer used to receive the option in, and this buffer is returned as a string. It is up to the caller to decode the contents of the buffer (see the optional built-in module struct for a way to decode C structures encoded as strings).

listen( backlog)
Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 1; the maximum value is system-dependent (usually 5).

makefile( [mode[, bufsize]])
Return a file object associated with the socket. (File objects are described in 3.9, “File Objects.”) The file object references a dup()ped version of the socket file descriptor, so the file object and socket object may be closed or garbage-collected independently. The socket must be in blocking mode. The optional mode and bufsize arguments are interpreted the same way as by the built-in file() function; see “Built-in Functions” (section 2.1) for more information.

recv( bufsize[, flags])
Receive data from the socket. The return value is a string representing the data received. The maximum amount of data to be received at once is specified by bufsize. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. Note: For best match with hardware and network realities, the value of bufsize should be a relatively small power of 2, for example, 4096.
从套接字获得数据。返回值是字符串格式的接收到的数据。一次接受数据的最大数量是 bufsize。参数 flags 的作用参考 Unix manual 的 recv(2) 页面,它的默认值是0。注意:最好与硬件和网络实现比配,bufsize 建议使用一个小值,例如:4096。

recvfrom( bufsize[, flags])
Receive data from the socket. The return value is a pair (string, address) where string is a string representing the data received and address is the address of the socket sending the data. The optional flags argument has the same meaning as for recv() above. (The format of address depends on the address family — see above.)
从套接字获得数据。返回值是(string,address),string 是字符串格式接收到的数据,address 是那个地址发送的这个数据。参数 flags 和 recv() 一样。(地址格式依赖于协议类型。)

recvfrom_into( buffer[, nbytes[, flags]])
Receive data from the socket, writing it into buffer instead of creating a new string. The return value is a pair (nbytes, address) where nbytes is the number of bytes received and address is the address of the socket sending the data. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. (The format of address depends on the address family — see above.) New in version 2.5.

recv_into( buffer[, nbytes[, flags]])
Receive up to nbytes bytes from the socket, storing the data into a buffer rather than creating a new string. If nbytes is not specified (or 0), receive up to the size available in the given buffer. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero. New in version 2.5.
从 socket 接收 nbytes 字节的数据,储存数据到 buffer 而不是创建一个新的字符串。如果 nbytes 没有指定(或者为0),那么接收buffer 可用空间的数据。flags 参数请查看 Unix manual recv(2) 页面,它的默认值是0。2.5版本新增。

send( string[, flags])
Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data.
向这个套接字发送数据。这个套接字必须已经连接远程套接字。flags 选项请参考recv()。返回值是已发送的字节数。应用程序有责任检查所有数据是是否全部发送。如果只有部分数据被发送,那么应用程序必须重新发送剩余的数据。

sendall( string[, flags])
Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Unlike send(), this method continues to send data from string until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent.
向这个套接字发送数据。这个套接字必须已经连接远程套接字。flags 选项请参考recv()。不同于 send(),本方法一直发送数据知道全部数据发送成功或者发生错误。成功是返回 None。发生错误时,一个异常被引发。不限制大量数据,即使大量数据也可以安全发送。

sendto( string[, flags], address)
Send data to the socket. The socket should not be connected to a remote socket, since the destination socket is specified by address. The optional flags argument has the same meaning as for recv() above. Return the number of bytes sent. (The format of address depends on the address family — see above.)

setblocking( flag)
Set blocking or non-blocking mode of the socket: if flag is 0, the socket is set to non-blocking, else to blocking mode. Initially all sockets are in blocking mode. In non-blocking mode, if a recv() call doesn’t find any data, or if a send() call can’t immediately dispose of the data, a error exception is raised; in blocking mode, the calls block until they can proceed. s.setblocking(0) is equivalent to s.settimeout(0); s.setblocking(1) is equivalent to s.settimeout(None).

settimeout( value)
Set a timeout on blocking socket operations. The value argument can be a nonnegative float expressing seconds, or None. If a float is given, subsequent socket operations will raise an timeout exception if the timeout period value has elapsed before the operation has completed. Setting a timeout of None disables timeouts on socket operations. s.settimeout(0.0) is equivalent to s.setblocking(0); s.settimeout(None) is equivalent to s.setblocking(1). New in version 2.3.

gettimeout( )
Return the timeout in floating seconds associated with socket operations, or None if no timeout is set. This reflects the last call to setblocking() or settimeout(). New in version 2.3.

Some notes on socket blocking and timeouts: A socket object can be in one of three modes: blocking, non-blocking, or timeout. Sockets are always created in blocking mode. In blocking mode, operations block until complete. In non-blocking mode, operations fail (with an error that is unfortunately system-dependent) if they cannot be completed immediately. In timeout mode, operations fail if they cannot be completed within the timeout specified for the socket. The setblocking() method is simply a shorthand for certain settimeout() calls.

Timeout mode internally sets the socket in non-blocking mode. The blocking and timeout modes are shared between file descriptors and socket objects that refer to the same network endpoint. A consequence of this is that file objects returned by the makefile() method must only be used when the socket is in blocking mode; in timeout or non-blocking mode file operations that cannot be completed immediately will fail.

Note that the connect() operation is subject to the timeout setting, and in general it is recommended to call settimeout() before calling connect().

setsockopt( level, optname, value)
Set the value of the given socket option (see the Unix manual page setsockopt(2)). The needed symbolic constants are defined in the socket module (SO_* etc.). The value can be an integer or a string representing a buffer. In the latter case it is up to the caller to ensure that the string contains the proper bits (see the optional built-in module struct for a way to encode C structures as strings).

shutdown( how)
Shut down one or both halves of the connection. If how is SHUT_RD, further receives are disallowed. If how is SHUT_WR, further sends are disallowed. If how is SHUT_RDWR, further sends and receives are disallowed.

Note that there are no methods read() or write(); use recv() and send() without flags argument instead.

Socket objects also have these (read-only) attributes that correspond to the values given to the socket constructor.

family
The socket family. New in version 2.5.

type
The socket type. New in version 2.5.

proto
The socket protocol. New in version 2.5.

No comment »

Python类库中文翻译:select — 等待 I/O 完成

15.1 select — Waiting for I/O completion

This module provides access to the select() and poll() functions available in most operating systems. Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since it was last read.
这个模块提供的 select() 和 poll() 方法可用于大部分操作系统。注意:在 Windows 下,它只能用于 sockets ;在其他系统下,它也可以用于其他类型(特别在 Unix 下,它还可以用于 管道)。它不能用来确定是否完成上次的对普通文件执行的读取操作。

The module defines the following:
这个模块定义下列内容:

exception error
异常错误
The exception raised when an error occurs. The accompanying value is a pair containing the numeric error code from errno and the corresponding string, as would be printed by the C function perror().
在发生错误将引发异常。accompanying 值包含错误代码和错误描述文本,用于使用 C 程序 perror() 打印。

poll( )
(Not supported by all operating systems.) Returns a polling object, which supports registering and unregistering file descriptors, and then polling them for I/O events; see section 15.1.1 below for the methods supported by polling objects.
(所有系统不支持。)

select( iwtd, owtd, ewtd[, timeout])
This is a straightforward interface to the Unix select() system call. The first three arguments are sequences of `waitable objects’: either integers representing file descriptors or objects with a parameterless method named fileno() returning such an integer. The three sequences of waitable objects are for input, output and `exceptional conditions’, respectively. Empty sequences are allowed, but acceptance of three empty sequences is platform-dependent. (It is known to work on Unix but not on Windows.) The optional timeout argument specifies a time-out as a floating point number in seconds. When the timeout argument is omitted the function blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks.
这对于 Ubix 系统调用 select() 来说是一个简单接口。前三个参数是‘等待对象’;????。这三个参数分别按顺序等待 输入、输出输出和异常状态。允许空数组,但是是否允许三个空序列依赖于平台。(已知支持 Unix 但是不支持 Windows。)timeout 参数接受浮点数表示的秒。如果省略 timeout 着阻塞到至少一个文件描述符准备就绪。timeout 为0表示从不阻塞。
译者注:在对方关闭连接的情况下(CLOSE_WAIT状态)会立即返回,并且处于可读列表里面。但是却会立即读到0长度的数据。建议在检测到连续多次读到0长度数据时关闭连接。

The return value is a triple of lists of objects that are ready: subsets of the first three arguments. When the time-out is reached without a file descriptor becoming ready, three empty lists are returned.
返回值是包含前三个参数里面已准备就绪的对象的3个列表.如果已经超时但是并没有对象准备就绪,那么返回3个空列表

Among the acceptable object types in the sequences are Python file objects (e.g. sys.stdin, or objects returned by open() or os.popen()), socket objects returned by socket.socket().You may also define a wrapper class yourself, as long as it has an appropriate fileno() method (that really returns a file descriptor, not just a random integer). Note: File objects on Windows are not acceptable, but sockets are. On Windows, the underlying select() function is provided by the WinSock library, and does not handle file descriptors that don’t originate from WinSock.
接受的对象类型按次序是 Python 文件对象(例如:sys.stdin 或者 open()或os.popen()返回的对象)或者socket.socket()返回的socket对象。你也可以定义一个类,只要它包含恰当的 fileno() 方法(它其实范围文件描述符,不要只是返回随机数)注意:windows 不接受文件对象,但是接受 sockets。在 windows 下 select() 程序隐式使用 WinSock 库,WinSock 并不支持文件对象句柄。

Subsections

* 15.1.1 Polling Objects

No comment »

Python类库中文翻译:BaseHTTPServer — 基本 HTTP 服务器

This module defines two classes for implementing HTTP servers (Web servers). Usually, this module isn’t used directly, but is used as a basis for building functioning Web servers. See the SimpleHTTPServer and CGIHTTPServer modules.
这个模块定义了两个类用来实现 HTTP 服务器(WEB服务器)。通常本模块不会直接使用。

The first class, HTTPServer, is a SocketServer.TCPServer subclass. It creates and listens at the HTTP socket, dispatching the requests to a handler. Code to create and run the server looks like this:
第一个类,HTTPServer 是一个 SocketServer.TCPServer 的子集。他创建并监听 HTTP 套接字,分配 requests 到处理器(handler)。编码创建并运行这个服务器看起来像这样:

def run(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = (”, 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()

class HTTPServer( server_address, RequestHandlerClass)
This class builds on the TCPServer class by storing the server address as instance variables named server_name and server_port. The server is accessible by the handler, typically through the handler’s server instance variable.

class BaseHTTPRequestHandler( request, client_address, server)
This class is used to handle the HTTP requests that arrive at the server. By itself, it cannot respond to any actual HTTP requests; it must be subclassed to handle each request method (e.g. GET or POST). BaseHTTPRequestHandler provides a number of class and instance variables, and methods for use by subclasses.

这个类在 HTTP 请求到达时处理它。实际上它自身并不能对任何 HTTP 请求作出响应,他必须存在派生类用来处理每一个请求方法(例如 GET 或者 POST)。BaseHTTPRequestHandler 为子集提供许多类变量、实例变量和方法。

The handler will parse the request and the headers, then call a method specific to the request type. The method name is constructed from the request. For example, for the request method “SPAM”, the do_SPAM() method will be called with no arguments. All of the relevant information is stored in instance variables of the handler. Subclasses should not need to override or extend the __init__() method.
这个处理器将分析请求对象和请求头部,然后根据请求类型调用相应的方法。这个方法名称根据请求类型建立。例子:如果请求方法为’SPAM’,那么 do_SOAM() 方法将无可争议的被调用。所有有关信息被存放在实例变量。派生类应该不需要理睬或扩展 __init() 方法。

BaseHTTPRequestHandler has the following instance variables:
BaseHTTPRequestHandler 拥有下列实例值:

client_address
Contains a tuple of the form (host, port) referring to the client’s address.

command
Contains the command (request type). For example, ‘GET’.
包含命令(请求类型)。例子:’GET’。

path
Contains the request path.
包含请求路径。

request_version
Contains the version string from the request. For example, ‘HTTP/1.0’.
包含请求的版本字符串。例子:’HTTP/1.0′

headers
Holds an instance of the class specified by the MessageClass class variable. This instance parses and manages the headers in the HTTP request.

rfile
Contains an input stream, positioned at the start of the optional input data.
包含输入流,从最初可选的输入数据开始。

wfile
Contains the output stream for writing a response back to the client. Proper adherence to the HTTP protocol must be used when writing to this stream.
包含一个用类写入响应的输出流。请遵守 HTTP 协议在适当的时候使用这个流。

BaseHTTPRequestHandler has the following class variables:
BaseHTTPRequestHandler 拥有下列类属性:

server_version
Specifies the server software version. You may want to override this. The format is multiple whitespace-separated strings, where each string is of the form name[/version]. For example, ‘BaseHTTP/0.2’.
指定服务器软件版本。你可以不理睬它。

sys_version
Contains the Python system version, in a form usable by the version_string method and the server_version class variable. For example, ‘Python/1.4’.
包含 Python 程序版本,用于 version_string 方法和 server_version 类变量。例子:’Python/1.4’。

error_message_format
Specifies a format string for building an error response to the client. It uses parenthesized, keyed format specifiers, so the format operand must be a dictionary. The code key should be an integer, specifying the numeric HTTP error code value. message should be a string containing a (detailed) error message of what occurred, and explain should be an explanation of the error code number. Default message and explain values can found in the responses class variable.
指定用于发送给客户端的错误回应使用的格式字符串。使用被括号括主的key格式,所以格式化参数必须包含在一个字典里面。code 键是一个整数,为 HTTP 错误代码。message 是一个字符串,为相信的错误消息。explain 是错误代码的说明。默认 message 和 explain 的值可以在responses 类里面找到。

protocol_version
This specifies the HTTP protocol version used in responses. If set to ‘HTTP/1.1’, the server will permit HTTP persistent connections; however, your server must then include an accurate Content-Length header (using send_header()) in all of its responses to clients. For backwards compatibility, the setting defaults to ‘HTTP/1.0’.
指定HTTP协议版本。如果你设定为’HTTP/1.1’,那么这个服务器支持持久连接。不管什么情况,你的服务器向客户端回应的所有响应(responses)必须包含准确的 Content-Length 头(使用 send_header())。为了向后兼容,默认设置为 ‘HTTP/1.0’ 。

MessageClass
Specifies a rfc822.Message-like class to parse HTTP headers. Typically, this is not overridden, and it defaults to mimetools.Message.

responses
This variable contains a mapping of error code integers to two-element tuples containing a short and long message. For example, {code: (shortmessage, longmessage)}. The shortmessage is usually used as the message key in an error response, and longmessage as the explain key (see the error_message_format class variable).
这个变量包含根据错误代码映射到包含两个长短消息的成员的 tuples 的字典。

A BaseHTTPRequestHandler instance has the following methods:
一个 BaseHTTPRequestHandler 视力拥有下列方法:

handle( )
Calls handle_one_request() once (or, if persistent connections are enabled, multiple times) to handle incoming HTTP requests. You should never need to override it; instead, implement appropriate do_*() methods.
调用 handle_one_request() 一次(如果激活持久连接,则多次)来处理新到达的请求。你应该从来不需要理睬它,而应该使用恰当的 do_*() 方法。

handle_one_request( )
This method will parse and dispatch the request to the appropriate do_*() method. You should never need to override it.
这个处理并分配请求到恰当的 do_*() 方法。你应该从来不需要理睬他。

send_error( code[, message])
Sends and logs a complete error reply to the client. The numeric code specifies the HTTP error code, with message as optional, more specific text. A complete set of headers is sent, followed by text composed using the error_message_format class variable.
为客户端发送一个完整的错误回应并记录它。code 指定了 HTTP 错误代码,可选的 message 提供了更详细的信息。一个完整的响应头被发送后,根据 erroe_message_format 生成的正文被发送。

send_response( code[, message])
Sends a response header and logs the accepted request. The HTTP response line is sent, followed by Server and Date headers. The values for these two headers are picked up from the version_string() and date_time_string() methods, respectively.
发送回应头和记录这个普通请求。HTTP 回应行发送完成后紧跟着发送 Server 和 Date 头。这两个值分别从 version_string() 和 date_time_string() 获得。

send_header( keyword, value)
Writes a specific HTTP header to the output stream. keyword should specify the header keyword, with value specifying its value.
向输出流写入指定的 HTTP 头。keyword 为 HTTP 头键,value 为 HTTP 头的值。

end_headers( )
Sends a blank line, indicating the end of the HTTP headers in the response.
发送一个空白行,标志着回应的 HTTP 头结束。

log_request( [code[, size]])
Logs an accepted (successful) request. code should specify the numeric HTTP code associated with the response. If a size of the response is available, then it should be passed as the size parameter.
记录一个成功的普通请求。code 指定为响应的HTTP代码。如果大小是确定的,那么应该传递到 size 参数。

log_error( …)
Logs an error when a request cannot be fulfilled. By default, it passes the message to log_message(), so it takes the same arguments (format and additional values).
记录什么时间的一个请求出错不能执行。默认,它转发消息到 log_message(),它使用一样参数(format 和 附加的参数)。

log_message( format, …)
Logs an arbitrary message to sys.stderr. This is typically overridden to create custom error logging mechanisms. The format argument is a standard printf-style format string, where the additional arguments to log_message() are applied as inputs to the formatting. The client address and current date and time are prefixed to every message logged.
记录任意格式消息到 sys.stderr。它通常被自定义的日子处理程序覆盖。format 参数是标准的 printf-style 格式字符串,由传入 log_message() 的额外参数用于格式化。客户端地址和当前日期和时间被附加在每一个日志消息前面。

version_string( )
Returns the server software’s version string. This is a combination of the server_version and sys_version class variables.
返回服务软件的版本字符串。这是 server_version 和 sys_version 的组合。

date_time_string( [timestamp])
Returns the date and time given by timestamp (which must be in the format returned by time.time()), formatted for a message header. If timestamp is omitted, it uses the current date and time.
根据 timestamp(必须是time.time()返回的格式) 返回时间和日期。如果 timestamp 不存在,那么它将使用当前日期和时间。

The result looks like ‘Sun, 06 Nov 1994 08:49:37 GMT’. New in version 2.5: The timestamp parameter.
他的结果看起来像’Sun, 06 Nov 1994 08:49:37 GMT’。2.5版本的新功能:timestamp 参数。

log_date_time_string( )
Returns the current date and time, formatted for logging.
返回格式化后的用于日志的当前日期和时间。

address_string( )
Returns the client address, formatted for logging. A name lookup is performed on the client’s IP address.
返回格式化后的用于日志的客户地址。对客户IP地址执行名称查询。
译注:真实使用时建议重写本方法为直接输出IP,执行名称查询会严重影响性能。

See Also:
参考:

Module CGIHTTPServer:
Extended request handler that supports CGI scripts.
扩展请求处理器以支持 CGI 脚本。

Module SimpleHTTPServer:
Basic request handler that limits response to files actually under the document root.
基本请求处理器,限制响应的文件范围为 document 目录之下。

译者注:建议继承者设置 rbufsize = 0 来关闭 self.rfile 的缓冲,用来防止少量数据 POST 时不会被 select.select 识别的问题

Comments (1) »