您的位置:首页 > 理论基础 > 计算机网络

Python网络编程2:创建套接字和套接字对象的内建方法

2013-04-23 16:35 423 查看
1.使用socket模块中socket()函数创建套接字:

socket()函数返回一个socket对象,该对象的方法实现了各种socket系统调用。

语法:

import socket

socket.socket([family[, type[, proto]]])

使用给定的address family, socket type和protocol number创建一个新的socket对象。

The address family(地址家族):AF_INET (默认), AF_INET6,AF_UNIX, AF_CAN 或者 AF_RDS。

The socket type(套接字类型):SOCK_STREAM (默认), SOCK_DGRAM, SOCK_RAW 或者 可能是其他SOCK_常量之一。

The protocol number(协议号):通常是0(这种情况下可以忽略) 或者 CAN_RAW(如果地址家族是AF_CAN)。

注意:AF_CAN family和AF_RDS家族是3.3版本中新增的。

例如:

(1)创建一个TCP/IP套接字

import socket

tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

(2)创建一个UDP/IP套接字

import socket

udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

或者为了简写:

from socket import *

tcpSock = socket(AF_INET, SOCK_STREAM)

udpSock = socket(AF_INET, SOCK_DGRAM)

2.套接字对象的方法

(1)服务器端套接字方法:

socket.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.)

将套接字绑定到地址。这个套接字必须是没有绑定过的。(地址的格式依赖于地址家族,例如AF_INET家族的套接字地址是(host,port)元组)。

socket.listen(backlog)

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

监听来自套接字的连接。backlog参数指定最大排队连接数,应至少为0。最大值是依赖于系统的(通常为5),最小值强制为0。

socket.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.

接受一个连接。这个套接字必须已经绑定到一个地址并且正在监听连接。该方法的返回值是一个元组(conn, address),其中conn是一个新的socket对象,该对象在连接时可用于发送和接受数据;address是一个地址,该地址被绑定于在连接另一端的套接字(socket)上。

(2)客户端套接字方法:

socket.connect(address)

Connect to a remote socket at address. (The format of address depends on the address family — see above.)

连接到在address上的远端套接字。(地址的格式依赖于地址家族,例如AF_INET家族的套接字地址是(host,port)元组)。connect(address)中使用的address地址和bind(address)中是相同的。

socket.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.

类似于connect(address),但是返回的是一个error indicator替代了通过C级别connect()调用返回针对错误抛出一个异常。如果操作成功,error indicator是0,否则是errno变量的值。这是非常有用的支持,例如,异步连接。

(3)公共用途的套接字方法

socket.recv(bufsize[, flags])

Receive data from the socket. The return value is a bytes object 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指定。查看Unix手册recv(2)中可选参数flags的含义;它默认为0。

注意:针对硬件和网络实际情况的最佳匹配,BUFSIZE的值应该是一个相对较小的2的幂,例如,4096。

socket.recvfrom(bufsize[, flags])

Receive data from the socket. The return value is a pair (bytes, address) where bytes is a bytes object representing the data 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.)

接收来自套接字的数据。该方法的返回值是一个元组(bytes, address),其中bytes是一个字节对象,它表示已接受到的数据;address是一个发送数据的套接字的地址。查看Unix手册recv(2)中可选参数flags的含义;它默认为0。(address的格式依赖于地址家族,例如AF_INET家族的套接字地址是(host,port)元组)

socket.send(bytes[, 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. For further information on this topic, consult the Socket Programming HOWTO.

发送数据到socket。这个套接字必须连接到一个远端的套接字。可选的flags参数和recv()中有相同的意义。该方法返回发送的字节数目。应用程序负责检查所有数据已经被发送;如果只有部分数据已经被发送,那么应用程序需要尝试发送剩下的数据。关于这个话题的进一步的信息,请查阅the Socket Programming HOWTO

socket.sendall(bytes[, 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 bytes 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.

发送数据到socket。这个套接字必须连接到一个远端的套接字。可选的flags参数和recv()中有相同的意义。和send()不同,这个方法会连续发送数据(从字节对象)直到所有数据发送完毕或发送错误。成功时返回None。发生错误,会抛出一个异常,如果有数据的话,也没有办法确定有多少数据已经成功发送。

socket.sendto(bytes, address)socket.sendto(bytes, 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.)

发送数据到socket。这个套接字不应该连接到一个远端的套接字,由于目的套接字被地址(address)指定。可选的flags参数和recv()中有相同的意义。该方法返回发送的字节数目。(地址的格式依赖于地址家族,例如AF_INET家族的套接字地址是(host,port)元组)

socket.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.

Note:close() releases the resource associated with a connection but does not necessarily close the connection immediately. If you want to close the connection in a timely fashion, call shutdown() before close().

关闭套接字。在这个套接字上将要进行的所有操作都将失败。远端将不再接收数据(排队的数据刷新后)。当套接字进行垃圾回收是自动关闭。

注意:close()会释放与连接相关的资源,但是不一定立即关闭关联。如果想要及时关闭连接,在调用call()前调用shutdown()。

socket.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.

返回连接到当前套接字的远端地址。例如,这非常有利于找出一个远端IPv4/IPv6套接字的端口号。(address的格式依赖于地址家族,例如AF_INET家族的套接字地址是(host,port)元组)。在许多系统中这个函数不支持。

socket.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.)

返回当前套接字的地址。例如,这非常有利于找出一个IPv4/IPv6套接字的端口号。(address的格式依赖于地址家族,例如AF_INET家族的套接字地址是(host,port)元组)。

socket.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 bytes object. 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 byte strings).

返回给定的套接字选项的值。

socket.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 bytes object representing a buffer. In the latter case it is up to the caller to ensure that the bytestring contains the proper bits (see the optional built-in module struct for a way to encode C structures as bytestrings).

设置给定的套接字选项的值。

(4)面向阻塞的套接字方法

socket.setblocking(flag)

Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking, else to blocking mode.

This method is a shorthand for certain settimeout() calls:

sock.setblocking(True) is equivalent to sock.settimeout(None)

sock.setblocking(False) is equivalent to sock.settimeout(0.0)

设置套接字的阻塞与非阻塞模式:如果flag为false,这个套接字设置为非阻塞模式,否则设置为阻塞模式。

sock.setblocking(True)等价于sock.settimeout(None)

sock.setblocking(False)等价于sock.settimeout(0.0)

socket.settimeout(value)

Set a timeout on blocking socket operations. The value argument can be a nonnegative floating point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations will raise a timeout exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode.

For further information, please consult the notes on socket timeouts.

设置阻塞套接字操作的超时时间。

socket.gettimeout()

Return the timeout in seconds (float) associated with socket operations, or None if no timeout is set. This reflects the last call to setblocking() orsettimeout().

得到阻塞套接字操作的超时时间。

(5)面向文件的套接字函数

socket.fileno()

Return the socket’s file descriptor (a small integer). This is useful with 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.

返回套接字的文件描述符(一个很小的整数)。

socket.makefile(mode='r', buffering=None, *, encoding=None, errors=None, newline=None)

Return a file object associated with the socket. The exact returned type depends on the arguments given to makefile(). These arguments are interpreted the same way as by the built-in open() function.

Closing the file object won’t close the socket unless there are no remaining references to the socket. The socket must be in blocking mode; it can have a timeout, but the file object’s internal buffer may end up in a inconsistent state if a timeout occurs.

Note:

On Windows, the file-like object created by makefile() cannot be used where a file object with a file descriptor is expected, such as the stream arguments of subprocess.Popen().

返回一个与套接字相关的文件对象。

socket对象的相关方法的参考官方文档地址:http://docs.python.org/3/library/socket.html#module-socket
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: