套接字学习:资料总结,python socket document学习总结

来源:互联网 发布:合肥有mac专柜吗 编辑:程序博客网 时间:2024/05/13 02:36

套接字学习:资料总结,python socket document学习总结

本文未整理完毕,还在学习中。。。持续更新ing。。。

Socket Object's Method

以下为官网例子的代码:

# Echo server programimport socketHOST = '127.0.0.1'                 # Symbolic name meaning all available interfacesPORT = 11111              # Arbitrary non-privileged ports = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.bind((HOST, PORT))s.listen(1)conn, addr = s.accept()print 'Connected by', addrwhile 1:    data = conn.recv(1024)    if not data: break    conn.sendall(data)conn.close()
# Echo client programimport socketHOST = '127.0.0.1'    # The remote hostPORT = 11111              # The same port as used by the servers = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((HOST, PORT))s.sendall('Hello, world')data = s.recv(1024)s.close()print 'Received', repr(data)

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

原文:Create a new socket using the given address family, socket type and protocol number. The address family should be AF_INET(the default), AF_INET6 or AF_UNIX. The socket type should be SOCK_STREAM (the default), SOCK_DGRAM or perhaps one of the other SOCK_ constants. The protocol number is usually zero and may be omitted in that case.

family参数为:socket.AF_UNIX,socket.AF_INET,socket.AF_INET6三种类型。
type参数为:socket.SOCK_STREAM(流套接字socket.SOCK_DGRAM(数据报文套接字)socket.SOCK_RAW(原始套接字)socket.SOCK_RDM,socket.SOCK_SEQPACKET

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

把socket绑定到一个没有绑定的可用地址。

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.

监听连接到socket的连接。backlog参数指定最大连接数,至少为0,最大值一般由系统决定(一般为5)。

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.

在上面例子里,我们用socket.accept()得到一个连接。这个socket必须绑定(bind)了服务器的address(HOST)并listen指定的没有使用的PORT。当客户端client连接(connection)了这个socket时,accept()方法获得这个client的地址和一个新的socket对象conn,对象conn用于和client进行通信,地址绑定在客户端client的socket上。

也就是说accept()用于创建好server的socket后接受listen到的信息(conn, address)

socket.connect(address)

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

连接到一个远程socket(客户端连到服务端)。

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.

类似content(),但是用一个错误指示代替抛出异常。如果成功,返回0,否则返回错误类型。【用于支持异步连接】

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.

关闭socket。

socket.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 argumentflags; it defaults to zero.
从socket接受数据。返回的数据是一个字符串【也就是只能是字符串】!bufsize指定了每次最大的接收数据量。
Note:为了最佳匹配硬件和网络,bufsize最好为2的指数,例如4096。
接收TCP数据

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

从socket接收数据。返回(string, address),string为字符串表示的数据,address为发送端的地址。

接收UDP数据

socket.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 addressdepends on the address family — see above.)

从socket接收数据。与上面两个方法不一样的是把数据写入buffer而不是给一个字符串变量。返回(nbytes, address),nbytes是接收数据的字节数,address是发送端地址。

socket.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 nbytesis not specified (or 0), receive up to the size available in the given buffer. Returns the number of bytes received. See the Unix manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.

从socket接收nbytes个字节的数据,写入buffer。如果nbytesis没有指定或者是0的话,接收数据大小由buffer的大小决定,最后返回接收数据的字节数给发送端。

socket.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. For further information on this concept, consult the Socket Programming HOWTO.

发送数据到socket,这个socket必须连接到一个远程的socket。返回成功发送数据的字节数。应用程序负责检查所有数据是否全部成功发送;如果一些没发送成功,应用程序需要尝试再次发送数据。

发送TCP数据

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

发送数据到socket,这个socket必须连接到一个远程的socket。不同于send()方法,这个方法一直发送数据,直到发完或者一个错误发生。成功没有返回标记,错误则抛出一个异常。没有办法知道正确发送了多少数据,除非你全部发送成功。

完整发送TCP数据

socket.sendto(stringflagsaddress)

原文: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,这个socket不必连接到远程socket,因为目的地由address指定!返回已成功发送的字节数。

发送UDP数据

socket.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.0)s.setblocking(1) is equivalent to s.settimeout(None).

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 asos.fdopen()). Unix does not have this limitation.

返回socket的文件描述符(小整数)。和select.select()配合使用。

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.

返回远程socket的address。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.)

返回当前socket的address。PORT

socket.getsockopt(leveloptname[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).

返回指定socket参数的value。如果缓冲区长度没有指定,则假设有一个整数选项并返回他的value。如果缓冲区长度指定了,则返回一个string。由应用程序解码buffer!

socket.setsockopt(leveloptnamevalue)

原文: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 structfor a way to encode C structures as strings).

设置给定的socket参数的值。

socket.makefile([mode[bufsize]])

面向文件的套接字函数
原文:Return a file object associated with the socket. (File objects are described in 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 (it can not have a timeout). The optional mode andbufsize arguments are interpreted the same way as by the built-in file() function.

返回一个与socket关联的file对象。socket必须在阻塞模式(不能有timeout)。mode和bufsize参数和file()里面一样。

windows平台需要注意: 

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.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.0)s.setblocking(1) is equivalent to s.settimeout(None).

设置socket的模式为非阻塞或者阻塞。flag=0,socket为非阻塞模式,else为阻塞模式。没设置前默认为阻塞模式。在非阻塞模式下,如果recv()接收不到数据或者send()不能立即发送数据,会抛出错误异常;在阻塞模式,在处理前都会被阻塞。

s.setblocking(0) == s.settimeout(0.0) # 非阻塞模式

s.setblocking(1) == s.settimeout(None) # 阻塞模式

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

在socket处于阻塞模式工作时设置一个超时。value可以是一个flout的数据,单位为秒,也可以是None。设置为float时,后续的socket操作会在本次操作未在timeout时间内完成的时候抛出timeout异常。设置为None时,也就是一只等待本次操作完成,处于阻塞模式。

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() or settimeout().

返回socket的超时值,值得单位为秒,float数据类型,或者为None(没有设置超时)。反映的是最后一次调用setblocking() or settimeout()的timeout值。

【备注:

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 or the system returns an error (such as connection timed out). 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 or if the system returns an error. 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() or pass a timeout parameter to create_connection(). The system network stack may return a connection timeout error of its own regardless of any Python socket timeout setting.

socket.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. Depending on the platform, shutting down one half of the connection can also close the opposite half (e.g. on Mac OS X, shutdown(SHUT_WR) does not allow further reads on the other end of the connection).

关闭一个或者所有的半开放式socket()。how参数为为SHUT_RD时,不再接收数据;参数为SHUT_WR时,不再发送;参数为SHUT_RDWR,发送接收都不允许。有些平台关闭一个半开放的socket也会关闭远程的半开放socket。

这一块内容可参考:Socket之shutdown()用法

socket.ioctl(controloption) windows平台

程序错误处理

socket.error: [Errno10048]Onlyoneusageofeach socket address

错误原因,只能一个有一个socket绑定地址,也就是服务器程序开多了!同一个PORT上)。检查下server.py开了几个。

0 0
原创粉丝点击