Python网络编程2:创建套接字和套接字对象的内建方法
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。這個套接字必須連接到一個遠端的套接字??蛇x的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。這個套接字必須連接到一個遠端的套接字??蛇x的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
?
轉載于:https://www.cnblogs.com/fortwo/archive/2013/04/23/3038123.html
總結
以上是生活随笔為你收集整理的Python网络编程2:创建套接字和套接字对象的内建方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: golang 数组
- 下一篇: 多线程并发:每个开发人员都应了解的内容