继承者: QUdpSocket , QTcpSocket , QSslSocket
PySide.QtNetwork.QAbstractSocket class provides the base functionality common to all socket types.
PySide.QtNetwork.QAbstractSocket is the base class for PySide.QtNetwork.QTcpSocket and PySide.QtNetwork.QUdpSocket 及包含这 2 个类的所有常用功能。若需要套接字,有 2 选项:
TCP (传输控制协议) 是可靠、面向流、面向连接的传输协议。UDP (用户数据报协议) 是不可靠,面向数据报的无连接协议。在实践中,这意味着 TCP 更适合连续数据传输,可以使用更轻量的 UDP 当可靠性不重要时。
PySide.QtNetwork.QAbstractSocket ‘s API unifies most of the differences between the two protocols. For example, although UDP is connectionless, PySide.QtNetwork.QAbstractSocket.connectToHost() establishes a virtual connection for UDP sockets, enabling you to use PySide.QtNetwork.QAbstractSocket in more or less the same way regardless of the underlying protocol. Internally, PySide.QtNetwork.QAbstractSocket remembers the address and port passed to PySide.QtNetwork.QAbstractSocket.connectToHost() , and functions like PySide.QtCore.QIODevice.read() and PySide.QtCore.QIODevice.write() use these values.
At any time, PySide.QtNetwork.QAbstractSocket has a state (returned by PySide.QtNetwork.QAbstractSocket.state() ). The initial state is UnconnectedState . After calling PySide.QtNetwork.QAbstractSocket.connectToHost() , the socket first enters HostLookupState . If the host is found, PySide.QtNetwork.QAbstractSocket 进入 ConnectingState and emits the PySide.QtNetwork.QAbstractSocket.hostFound() signal. When the connection has been established, it enters ConnectedState 并发射 PySide.QtNetwork.QAbstractSocket.connected() . If an error occurs at any stage, PySide.QtNetwork.QAbstractSocket.error() is emitted. Whenever the state changes, PySide.QtNetwork.QAbstractSocket.stateChanged() is emitted. For convenience, PySide.QtNetwork.QAbstractSocket.isValid() returns true if the socket is ready for reading and writing, but note that the socket's state must be ConnectedState 在读写可以发生之前。
Read or write data by calling PySide.QtCore.QIODevice.read() or PySide.QtCore.QIODevice.write() , or use the convenience functions PySide.QtCore.QIODevice.readLine() and PySide.QtCore.QIODevice.readAll() . PySide.QtNetwork.QAbstractSocket also inherits PySide.QtCore.QIODevice.getChar() , PySide.QtCore.QIODevice.putChar() ,和 PySide.QtCore.QIODevice.ungetChar() from PySide.QtCore.QIODevice , which work on single bytes. The PySide.QtCore.QIODevice.bytesWritten() signal is emitted when data has been written to the socket (i.e., when the client has read the data). Note that Qt does not limit the write buffer size. You can monitor its size by listening to this signal.
PySide.QtCore.QIODevice.readyRead() signal is emitted every time a new chunk of data has arrived. PySide.QtNetwork.QAbstractSocket.bytesAvailable() then returns the number of bytes that are available for reading. Typically, you would connect the PySide.QtCore.QIODevice.readyRead() signal to a slot and read all available data there. If you don't read all the data at once, the remaining data will still be available later, and any new incoming data will be appended to PySide.QtNetwork.QAbstractSocket ‘s internal read buffer. To limit the size of the read buffer, call PySide.QtNetwork.QAbstractSocket.setReadBufferSize() .
要关闭套接字,调用 PySide.QtNetwork.QAbstractSocket.disconnectFromHost() . PySide.QtNetwork.QAbstractSocket 进入 QAbstractSocket.ClosingState . After all pending data has been written to the socket, PySide.QtNetwork.QAbstractSocket actually closes the socket, enters QAbstractSocket::ClosedState, and emits PySide.QtNetwork.QAbstractSocket.disconnected() . If you want to abort a connection immediately, discarding all pending data, call PySide.QtNetwork.QAbstractSocket.abort() instead. If the remote host closes the connection, PySide.QtNetwork.QAbstractSocket will emit error( QAbstractSocket.RemoteHostClosedError ), during which the socket state will still be ConnectedState , and then the PySide.QtNetwork.QAbstractSocket.disconnected() signal will be emitted.
The port and address of the connected peer is fetched by calling PySide.QtNetwork.QAbstractSocket.peerPort() and PySide.QtNetwork.QAbstractSocket.peerAddress() . PySide.QtNetwork.QAbstractSocket.peerName() returns the host name of the peer, as passed to PySide.QtNetwork.QAbstractSocket.connectToHost() . PySide.QtNetwork.QAbstractSocket.localPort() and PySide.QtNetwork.QAbstractSocket.localAddress() return the port and address of the local socket.
PySide.QtNetwork.QAbstractSocket provides a set of functions that suspend the calling thread until certain signals are emitted. These functions can be used to implement blocking sockets:
举例说明:
numRead = 0
numReadTotal = 0
while(True):
buffer = socket.read(50)
# do whatever with array
numReadTotal += buffer.size()
if (buffer.size() == 0 && !socket.waitForReadyRead()):
break
若 PySide.QtCore.QIODevice.waitForReadyRead() returns false, the connection has been closed or an error has occurred.
Programming with a blocking socket is radically different from programming with a non-blocking socket. A blocking socket doesn't require an event loop and typically leads to simpler code. However, in a GUI application, blocking sockets should only be used in non-GUI threads, to avoid freezing the user interface. See the network/fortuneclient and network/blockingfortuneclient examples for an overview of both approaches.
注意
We discourage the use of the blocking functions together with signals. One of the two possibilities should be used.
PySide.QtNetwork.QAbstractSocket can be used with PySide.QtCore.QTextStream and PySide.QtCore.QDataStream ‘s stream operators (operator<<() and operator>>()). There is one issue to be aware of, though: You must make sure that enough data is available before attempting to read it using operator>>().
| 参数: |
|
|---|
Creates a new abstract socket of type socketType 。 parent 自变量会被传递给 PySide.QtCore.QObject ‘s constructor.
此枚举描述传输层协议。
| 常量 | 描述 |
|---|---|
| QAbstractSocket.TcpSocket | TCP |
| QAbstractSocket.UdpSocket | UDP |
| QAbstractSocket.UnknownSocketType | Other than TCP and UDP |
此枚举描述可以发生的套接字错误。
| 常量 | 描述 |
|---|---|
| QAbstractSocket.ConnectionRefusedError | 连接被对等方拒绝 (或超时)。 |
| QAbstractSocket.RemoteHostClosedError | The remote host closed the connection. Note that the client socket (i.e., this socket) will be closed after the remote close notification has been sent. |
| QAbstractSocket.HostNotFoundError | 找不到主机地址。 |
| QAbstractSocket.SocketAccessError | 套接字操作失败,因为应用程序缺乏所需特权。 |
| QAbstractSocket.SocketResourceError | 本地系统资源不足 (如:太多套接字)。 |
| QAbstractSocket.SocketTimeoutError | 套接字操作超时。 |
| QAbstractSocket.DatagramTooLargeError | 数据报大于操作系统的限制 (可以低至 8192 字节)。 |
| QAbstractSocket.NetworkError | An error occurred with the network (e.g., the network cable was accidentally plugged out). |
| QAbstractSocket.AddressInUseError | The address specified to QUdpSocket.bind() is already in use and was set to be exclusive. |
| QAbstractSocket.SocketAddressNotAvailableError | The address specified to QUdpSocket.bind() does not belong to the host. |
| QAbstractSocket.UnsupportedSocketOperationError | The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support). |
| QAbstractSocket.ProxyAuthenticationRequiredError | The socket is using a proxy, and the proxy requires authentication. |
| QAbstractSocket.SslHandshakeFailedError | The SSL/TLS handshake failed, so the connection was closed (only used in PySide.QtNetwork.QSslSocket ) (This value was introduced in 4.4.) |
| QAbstractSocket.UnfinishedSocketOperationError | Used by QAbstractSocketEngine only, The last operation attempted has not finished yet (still in progress in the background). (This value was introduced in 4.4.) |
| QAbstractSocket.ProxyConnectionRefusedError | Could not contact the proxy server because the connection to that server was denied (This value was introduced in 4.5.) |
| QAbstractSocket.ProxyConnectionClosedError | The connection to the proxy server was closed unexpectedly (before the connection to the final peer was established) (This value was introduced in 4.5.) |
| QAbstractSocket.ProxyConnectionTimeoutError | The connection to the proxy server timed out or the proxy server stopped responding in the authentication phase. (This value was introduced in 4.5.) |
| QAbstractSocket.ProxyNotFoundError | The proxy address set with PySide.QtNetwork.QAbstractSocket.setProxy() (or the application proxy) was not found. (This value was introduced in 4.5.) |
| QAbstractSocket.ProxyProtocolError | The connection negotiation with the proxy server because the response from the proxy server could not be understood. (This value was introduced in 4.5.) |
| QAbstractSocket.UnknownSocketError | 发生无法识别的错误。 |
This enum describes the network layer protocol values used in Qt.
| 常量 | 描述 |
|---|---|
| QAbstractSocket.IPv4Protocol | IPv4 |
| QAbstractSocket.IPv6Protocol | IPv6 |
| QAbstractSocket.UnknownNetworkLayerProtocol | 除了 IPv4 和 IPv6 |
This enum represents the options that can be set on a socket. If desired, they can be set after having received the PySide.QtNetwork.QAbstractSocket.connected() signal from the socket or after having received a new socket from a PySide.QtNetwork.QTcpServer .
| 常量 | 描述 |
|---|---|
| QAbstractSocket.LowDelayOption | Try to optimize the socket for low latency. For a PySide.QtNetwork.QTcpSocket this would set the TCP_NODELAY option and disable Nagle's algorithm. Set this to 1 to enable. |
| QAbstractSocket.KeepAliveOption | Set this to 1 to enable the SO_KEEPALIVE socket option |
| QAbstractSocket.MulticastTtlOption | Set this to an integer value to set IP_MULTICAST_TTL (TTL for multicast datagrams) socket option. |
| QAbstractSocket.MulticastLoopbackOption | Set this to 1 to enable the IP_MULTICAST_LOOP (multicast loopback) socket option. |
注意
该枚举在 Qt 4.6 引入或被修改
此枚举描述套接字可以处于的不同状态。
| 常量 | 描述 |
|---|---|
| QAbstractSocket.UnconnectedState | 套接字未连接。 |
| QAbstractSocket.HostLookupState | 套接字正在履行主机名查找。 |
| QAbstractSocket.ConnectingState | 套接字开始建立连接。 |
| QAbstractSocket.ConnectedState | 已建立连接。 |
| QAbstractSocket.BoundState | The socket is bound to an address and port (for servers). |
| QAbstractSocket.ClosingState | 套接字即将关闭 (数据可能仍在等待被写入)。 |
| QAbstractSocket.ListeningState | 仅供内部使用。 |
中止当前连接并重置套接字。不像 PySide.QtNetwork.QAbstractSocket.disconnectFromHost() , this function immediately closes the socket, discarding any pending data in the write buffer.
另请参阅
PySide.QtNetwork.QAbstractSocket.disconnectFromHost() PySide.QtNetwork.QAbstractSocket.close()
| 参数: |
|
|---|
| 参数: |
|
|---|
| 参数: |
|
|---|
试图关闭套接字。若有等待写入的待决数据, PySide.QtNetwork.QAbstractSocket 将进入 ClosingState 并等待直到所有数据被写入。最终,它将进入 UnconnectedState and emit the PySide.QtNetwork.QAbstractSocket.disconnected() 信号。
Contains the implementation of PySide.QtNetwork.QAbstractSocket.disconnectFromHost() .
| 返回类型: | PySide.QtNetwork.QAbstractSocket.SocketError |
|---|
返回最后发生的错误类型。
另请参阅
PySide.QtNetwork.QAbstractSocket.state() PySide.QtCore.QIODevice.errorString()
| 参数: | arg__1 – PySide.QtNetwork.QAbstractSocket.SocketError |
|---|
| 返回类型: | PySide.QtCore.bool |
|---|
This function writes as much as possible from the internal write buffer to the underlying network socket, without blocking. If any data was written, this function returns true; otherwise false is returned.
调用此函数若需要 PySide.QtNetwork.QAbstractSocket 立即开始发送缓冲数据。成功写入的字节数从属操作系统。在大多数情况下,不需调用此函数,因为 PySide.QtNetwork.QAbstractSocket 将开始自动发送数据,一旦控制回到事件循环。若缺乏事件循环,调用 PySide.QtNetwork.QAbstractSocket.waitForBytesWritten() 代替。
另请参阅
PySide.QtCore.QIODevice.write() PySide.QtNetwork.QAbstractSocket.waitForBytesWritten()
| 返回类型: | PySide.QtCore.bool |
|---|
Returns true if the socket is valid and ready for use; otherwise returns false.
注意
套接字的状态必须为 ConnectedState 在读写可以发生之前。
| 返回类型: | PySide.QtNetwork.QHostAddress |
|---|
Returns the host address of the local socket if available; otherwise returns QHostAddress.Null .
This is normally the main IP address of the host, but can be QHostAddress.LocalHost (127.0.0.1) for connections to the local host.
| 返回类型: | PySide.QtCore.quint16 |
|---|
Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.
| 返回类型: | PySide.QtNetwork.QHostAddress |
|---|
Returns the address of the connected peer if the socket is in ConnectedState ;否则返回 QHostAddress.Null .
| 返回类型: | unicode |
|---|
返回对等方名称,指定通过 PySide.QtNetwork.QAbstractSocket.connectToHost() , or an empty PySide.QtCore.QString if PySide.QtNetwork.QAbstractSocket.connectToHost() has not been called.
| 返回类型: | PySide.QtCore.quint16 |
|---|
Returns the port of the connected peer if the socket is in ConnectedState ; otherwise returns 0.
| 返回类型: | PySide.QtNetwork.QNetworkProxy |
|---|
返回此套接字的网络代理。默认情况下 QNetworkProxy.DefaultProxy is used, which means this socket will query the default proxy settings for the application.
| 参数: |
|
|---|
| 返回类型: | PySide.QtCore.qint64 |
|---|
返回内部读取缓冲尺寸。这限制客户端可以接收的数据量先于调用 PySide.QtCore.QIODevice.read() or PySide.QtCore.QIODevice.readAll() .
A read buffer size of 0 (the default) means that the buffer has no size limit, ensuring that no data is lost.
另请参阅
PySide.QtNetwork.QAbstractSocket.setReadBufferSize() PySide.QtCore.QIODevice.read()
| 参数: | address – PySide.QtNetwork.QHostAddress |
|---|
Sets the address on the local side of a connection to address .
You can call this function in a subclass of PySide.QtNetwork.QAbstractSocket to change the return value of the PySide.QtNetwork.QAbstractSocket.localAddress() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.
Note that this function does not bind the local address of the socket prior to a connection (e.g., QUdpSocket.bind() ).
| 参数: | port – PySide.QtCore.quint16 |
|---|
Sets the port on the local side of a connection to port .
You can call this function in a subclass of PySide.QtNetwork.QAbstractSocket to change the return value of the PySide.QtNetwork.QAbstractSocket.localPort() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.
Note that this function does not bind the local port of the socket prior to a connection (e.g., QUdpSocket.bind() ).
| 参数: | address – PySide.QtNetwork.QHostAddress |
|---|
Sets the address of the remote side of the connection to address .
You can call this function in a subclass of PySide.QtNetwork.QAbstractSocket to change the return value of the PySide.QtNetwork.QAbstractSocket.peerAddress() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.
| 参数: | name – unicode |
|---|
Sets the host name of the remote peer to name .
You can call this function in a subclass of PySide.QtNetwork.QAbstractSocket to change the return value of the PySide.QtNetwork.QAbstractSocket.peerName() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.
| 参数: | port – PySide.QtCore.quint16 |
|---|
Sets the port of the remote side of the connection to port .
You can call this function in a subclass of PySide.QtNetwork.QAbstractSocket to change the return value of the PySide.QtNetwork.QAbstractSocket.peerPort() function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.
| 参数: | networkProxy – PySide.QtNetwork.QNetworkProxy |
|---|
将此套接字的显式网络代理设为 networkProxy .
要禁用此套接字所用代理,使用 QNetworkProxy.NoProxy 代理类型:
socket.setProxy(QNetworkProxy.NoProxy)
代理默认值为 QNetworkProxy.DefaultProxy , which means the socket will use the application settings: if a proxy is set with QNetworkProxy::setApplicationProxy, it will use that; otherwise, if a factory is set with QNetworkProxyFactory::setApplicationProxyFactory, it will query that factory with type QNetworkProxyQuery.TcpSocket .
| 参数: | size – PySide.QtCore.qint64 |
|---|
设置尺寸为 PySide.QtNetwork.QAbstractSocket ‘s internal read buffer to be size 字节。
若缓冲尺寸被限制到某个大小, PySide.QtNetwork.QAbstractSocket 不会缓冲超过此大小的数据。例外,0 缓冲尺寸意味着读取缓冲是无限的且缓冲所有传入数据。这是默认值。
此选项是有用的若仅在某时间点读取数据 (如:在实时流应用程序中),或者,若希望保护套接字以免接收太多数据 (可能最终导致应用程序内存不足)。
Only PySide.QtNetwork.QTcpSocket 使用 PySide.QtNetwork.QAbstractSocket ‘s internal buffer; PySide.QtNetwork.QUdpSocket does not use any buffering at all, but rather relies on the implicit buffering provided by the operating system. Because of this, calling this function on PySide.QtNetwork.QUdpSocket 不起作用。
另请参阅
PySide.QtNetwork.QAbstractSocket.readBufferSize() PySide.QtCore.QIODevice.read()
| 参数: |
|
|---|---|
| 返回类型: |
PySide.QtCore.bool |
| 参数: | socketError – PySide.QtNetwork.QAbstractSocket.SocketError |
|---|
Sets the type of error that last occurred to socketError .
另请参阅
PySide.QtNetwork.QAbstractSocket.setSocketState() PySide.QtCore.QIODevice.setErrorString()
| 参数: |
|
|---|
| 参数: | state – PySide.QtNetwork.QAbstractSocket.SocketState |
|---|
把套接字的状态设为 state .
| 返回类型: | PySide.QtCore.int |
|---|
返回本地套接字描述符为 PySide.QtNetwork.QAbstractSocket 对象若这是可用的;否则返回 -1。
If the socket is using PySide.QtNetwork.QNetworkProxy ,返回的描述符可能不能用于本机套接字函数。
套接字描述符不可用当 PySide.QtNetwork.QAbstractSocket 是在 UnconnectedState .
| 参数: | option – PySide.QtNetwork.QAbstractSocket.SocketOption |
|---|---|
| 返回类型: | object |
| 返回类型: | PySide.QtNetwork.QAbstractSocket.SocketType |
|---|
返回套接字类型 (TCP、UDP、或其它)。
| 返回类型: | PySide.QtNetwork.QAbstractSocket.SocketState |
|---|
返回套接字的状态。
| 参数: | arg__1 – PySide.QtNetwork.QAbstractSocket.SocketState |
|---|
| 参数: | msecs – PySide.QtCore.int |
|---|---|
| 返回类型: | PySide.QtCore.bool |
等待直到套接字被连接,最长 msecs milliseconds. If the connection has been established, this function returns true; otherwise it returns false. In the case where it returns false, you can call PySide.QtNetwork.QAbstractSocket.error() to determine the cause of the error.
以下范例最多等待 1 秒为建立连接:
socket.connectToHost("imap", 143)
if socket.waitForConnected(1000):
print "Connected!"
若 msecs 为 -1,此函数不会超时。
注意
This function may wait slightly longer than msecs , depending on the time it takes to complete the host lookup.
注意
Multiple calls to this functions do not accumulate the time. If the function times out, the connecting process will be aborted.
| 参数: | msecs – PySide.QtCore.int |
|---|---|
| 返回类型: | PySide.QtCore.bool |
等待直到套接字已断开连接,最长 msecs milliseconds. If the connection has been disconnected, this function returns true; otherwise it returns false. In the case where it returns false, you can call PySide.QtNetwork.QAbstractSocket.error() to determine the cause of the error.
以下范例最多等待 1 秒为关闭连接:
socket.disconnectFromHost()
if socket.state() == QAbstractSocket.UnconnectedState or \
socket.waitForDisconnected(1000):
print "Disconnected!"
若 msecs 为 -1,此函数不会超时。
另请参阅
PySide.QtNetwork.QAbstractSocket.disconnectFromHost() PySide.QtNetwork.QAbstractSocket.close()