The QAbstractSocket class provides the base functionality common to all socket types. 更多...
继承 QIODevice .
Inherited by QTcpSocket and QUdpSocket .
The QAbstractSocket class provides the base functionality common to all socket types.
QAbstractSocket 是基类,用于 QTcpSocket and QUdpSocket and contains all common functionality of these two classes. If you need a socket, you have two options:
TCP (Transmission Control Protocol) is a reliable, stream-oriented, connection-oriented transport protocol. UDP (User Datagram Protocol) is an unreliable, datagram-oriented, connectionless protocol. In practice, this means that TCP is better suited for continuous transmission of data, whereas the more lightweight UDP can be used when reliability isn't important.
QAbstractSocket's API unifies most of the differences between the two protocols. For example, although UDP is connectionless, connectToHost () establishes a virtual connection for UDP sockets, enabling you to use QAbstractSocket in more or less the same way regardless of the underlying protocol. Internally, QAbstractSocket remembers the address and port passed to connectToHost (),和 functions like read () 和 write () use these values.
At any time, QAbstractSocket has a state (returned by state ())。初始状态为 UnconnectedState . After calling connectToHost (), the socket first enters HostLookupState 。若 host is found, QAbstractSocket enters ConnectingState and 发射 hostFound () signal. When the connection has been established, it enters ConnectedState 并发射 connected (). If an error occurs at any stage, error () is emitted. Whenever the state changes, stateChanged () 被发射。 For convenience, isValid () returns true if the socket is ready for reading and writing, but note that the socket's state must be ConnectedState before reading and writing can occur.
Read or write data by calling read () 或 write (), or use the convenience 函数 readLine () 和 readAll (). QAbstractSocket also inherits getChar (), putChar (),和 ungetChar () from QIODevice , which work on single bytes. The 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 信号。
readyRead () signal is emitted every time a new chunk of data has arrived. bytesAvailable () then returns the number of bytes that are available for reading. Typically, you would connect the 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 QAbstractSocket's internal read buffer. To limit the size of the read buffer, call setReadBufferSize ().
要关闭套接字,调用 disconnectFromHost (). QAbstractSocket enters QAbstractSocket.ClosingState . After all pending data has been written to the socket, QAbstractSocket actually closes the socket, enters QAbstractSocket.ClosedState, and emits disconnected (). If you want to abort a connection immediately, discarding all pending data, call abort () instead. If the remote host closes the connection, QAbstractSocket will emit error( QAbstractSocket.RemoteHostClosedError ), during which the socket state will still be ConnectedState ,和 then the disconnected () signal will be emitted.
The port and address of the connected peer is fetched by calling peerPort () 和 peerAddress (). peerName () returns the host name of the peer, as passed to connectToHost (). localPort () 和 localAddress () return the port and address of the local socket.
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:
举例说明:
int numRead = 0, numReadTotal = 0;
char buffer[50];
forever {
numRead = socket.read(buffer, 50);
// do whatever with array
numReadTotal += numRead;
if (numRead == 0 && !socket.waitForReadyRead())
break;
}
若 waitForReadyRead() 返回 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.
QAbstractSocket can be used with QTextStream and 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>>().
This enum describes the network layer protocol values used in Qt.
| 常量 | 值 | 描述 |
|---|---|---|
| QAbstractSocket.IPv4Protocol | 0 | IPv4 |
| QAbstractSocket.IPv6Protocol | 1 | IPv6 |
| QAbstractSocket.UnknownNetworkLayerProtocol | -1 | 除了 IPv4 和 IPv6 |
另请参阅 QHostAddress.protocol ().
此枚举描述可以发生的套接字错误。
| 常量 | 值 | 描述 |
|---|---|---|
| QAbstractSocket.ConnectionRefusedError | 0 | The connection was refused by the peer (or timed out). |
| QAbstractSocket.RemoteHostClosedError | 1 | 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 | 2 | 找不到主机地址。 |
| QAbstractSocket.SocketAccessError | 3 | The socket operation failed because the application lacked the required privileges. |
| QAbstractSocket.SocketResourceError | 4 | The local system ran out of resources (e.g., too many sockets). |
| QAbstractSocket.SocketTimeoutError | 5 | 套接字操作超时。 |
| QAbstractSocket.DatagramTooLargeError | 6 | The datagram was larger than the operating system's limit (which can be as low as 8192 bytes). |
| QAbstractSocket.NetworkError | 7 | An error occurred with the network (e.g., the network cable was accidentally plugged out). |
| QAbstractSocket.AddressInUseError | 8 | The address specified to QUdpSocket.bind () is already in use and was set to be exclusive. |
| QAbstractSocket.SocketAddressNotAvailableError | 9 | The address specified to QUdpSocket.bind () does not belong to the host. |
| QAbstractSocket.UnsupportedSocketOperationError | 10 | The requested socket operation is not supported by the local operating system (e.g., lack of IPv6 support). |
| QAbstractSocket.ProxyAuthenticationRequiredError | 12 | The socket is using a proxy, and the proxy 要求身份验证。 |
| QAbstractSocket.SslHandshakeFailedError | 13 | The SSL/TLS handshake failed, so the connection was closed (only used in QSslSocket ) (This value was introduced in 4.4.) |
| QAbstractSocket.UnfinishedSocketOperationError | 11 | 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 | 14 | Could not contact the proxy server because the connection to that server was denied (This value was introduced in 4.5.) |
| QAbstractSocket.ProxyConnectionClosedError | 15 | 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 | 16 | 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 | 17 | The proxy address set with setProxy () (or the application proxy) was not found. (This value was introduced in 4.5.) |
| QAbstractSocket.ProxyProtocolError | 18 | 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 | -1 | 发生无法识别的错误。 |
另请参阅 QAbstractSocket.error ().
This enum represents the options that can be set on a socket. If desired, they can be set after having received the connected () signal from the socket or after having received a new socket from a QTcpServer .
| 常量 | 值 | 描述 |
|---|---|---|
| QAbstractSocket.LowDelayOption | 0 | Try to optimize the socket for low latency. 对于 QTcpSocket this would set the TCP_NODELAY option and disable Nagle's algorithm. Set this to 1 to enable. |
| QAbstractSocket.KeepAliveOption | 1 | Set this to 1 to enable the SO_KEEPALIVE socket option |
| QAbstractSocket.MulticastTtlOption | 2 | Set this to an integer value to set IP_MULTICAST_TTL (TTL for multicast datagrams) socket option. |
| QAbstractSocket.MulticastLoopbackOption | 3 | Set this to 1 to enable the IP_MULTICAST_LOOP (multicast loopback) socket option. |
该枚举在 Qt 4.6 引入或被修改。
另请参阅 QAbstractSocket.setSocketOption () and QAbstractSocket.socketOption ().
This enum describes the different states in which a socket can be.
| 常量 | 值 | 描述 |
|---|---|---|
| QAbstractSocket.UnconnectedState | 0 | 套接字未连接。 |
| QAbstractSocket.HostLookupState | 1 | The socket is performing a host name lookup. |
| QAbstractSocket.ConnectingState | 2 | The socket has started establishing a 连接。 |
| QAbstractSocket.ConnectedState | 3 | 已建立连接。 |
| QAbstractSocket.BoundState | 4 | The socket is bound to an address and port (for servers). |
| QAbstractSocket.ClosingState | 6 | The socket is about to close (data may still be waiting to be written). |
| QAbstractSocket.ListeningState | 5 | 仅供内部使用。 |
另请参阅 QAbstractSocket.state ().
此枚举描述传输层协议。
| 常量 | 值 | 描述 |
|---|---|---|
| QAbstractSocket.TcpSocket | 0 | TCP |
| QAbstractSocket.UdpSocket | 1 | UDP |
| QAbstractSocket.UnknownSocketType | -1 | Other than TCP and UDP |
另请参阅 QAbstractSocket.socketType ().
parent argument, if not None, causes self to be owned by Qt instead of PyQt.
Creates a new abstract socket of type socketType 。 parent 自变量会被传递给 QObject 的构造函数。
另请参阅 socketType (), QTcpSocket ,和 QUdpSocket .
中止当前连接并重置套接字。不像 disconnectFromHost (), this function immediately closes the socket, discarding any pending data in the write buffer.
另请参阅 disconnectFromHost () and close ().
重实现自 QIODevice.atEnd ().
Returns true if no more data is currently available for reading; otherwise returns false.
This function is most commonly used when reading data from the socket in a loop. For example:
// This slot is connected to QAbstractSocket.readyRead() void SocketClass.readyReadSlot() { while (!socket.atEnd()) { QByteArray data = socket.read(100); .... } }
另请参阅 bytesAvailable () 和 readyRead ().
重实现自 QIODevice.bytesAvailable ().
Returns the number of incoming bytes that are waiting to be read.
另请参阅 bytesToWrite () 和 read ().
重实现自 QIODevice.bytesToWrite ().
Returns the number of bytes that are waiting to be written. The bytes are written when control goes back to the event loop or when flush () 被调用。
另请参阅 bytesAvailable () 和 flush ().
重实现自 QIODevice.canReadLine ().
Returns true if a line of data can be read from the socket; otherwise returns false.
另请参阅 readLine ().
重实现自 QIODevice.close ().
Closes the I/O device for the socket, disconnects the socket's connection with the host, closes the socket, and resets the name, address, port number and underlying socket descriptor.
见 QIODevice.close () for a description of the actions that occur when an I/O device is closed.
另请参阅 abort ().
试图连接到 hostName on the given port .
套接字被打开采用给定 openMode and first 进入 HostLookupState ,那么 performs a host name lookup of hostName . If the lookup succeeds, hostFound () is emitted and QAbstractSocket 进入 ConnectingState . It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QAbstractSocket 进入 ConnectedState and 发射 connected ().
At any point, the socket can emit error () to signal that an error occurred.
hostName may be an IP address in string form (e.g., "43.195.83.32"), or it may be a host name (e.g., "example.com"). QAbstractSocket will do a lookup only if required. port is in native byte order.
另请参阅 state (), peerName (), peerAddress (), peerPort (),和 waitForConnected ().
这是重载函数。
试图连接到 address 在端口 port .
This method is also a Qt slot with the C++ signature void connectToHostImplementation(const QString&,quint16,QIODevice::OpenMode = QIODevice.ReadWrite) .
Contains the implementation of connectToHost ().
试图连接到 hostName on the given port . The socket is opened in the given openMode .
该函数在 Qt 4.1 引入。
Attempts to close the socket. If there is pending data waiting to be written, QAbstractSocket 将进入 ClosingState and wait until all data has been written. Eventually, it will enter UnconnectedState and emit the disconnected () 信号。
另请参阅 connectToHost ().
This method is also a Qt slot with the C++ signature void disconnectFromHostImplementation() .
Contains the implementation of disconnectFromHost ().
该函数在 Qt 4.1 引入。
返回最后发生的错误类型。
另请参阅 state () and errorString ().
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.
调用此函数若需要 QAbstractSocket to start sending buffered data immediately. The number of bytes successfully written depends on the operating system. In most cases, you do not need to call this function, because QAbstractSocket will start sending data automatically once control goes back to the event loop. In the absence of an event loop, call waitForBytesWritten () 代替。
另请参阅 write () 和 waitForBytesWritten ().
重实现自 QIODevice.isSequential ().
Returns true if the socket is valid and ready for use; otherwise returns false.
注意: 套接字的状态必须为 ConnectedState before reading and writing can occur.
另请参阅 state ().
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.
另请参阅 localPort (), peerAddress (),和 setLocalAddress ().
Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.
另请参阅 localAddress (), peerPort (),和 setLocalPort ().
Returns the address of the connected peer if the socket is in ConnectedState ; otherwise returns QHostAddress.Null .
另请参阅 peerName (), peerPort (), localAddress (),和 setPeerAddress ().
返回对等方名称,指定通过 connectToHost (), or an empty QString if connectToHost () has not been called.
另请参阅 peerAddress (), peerPort (),和 setPeerName ().
Returns the port of the connected peer if the socket is in ConnectedState ; otherwise returns 0.
另请参阅 peerAddress (), localPort (),和 setPeerPort ().
返回此套接字的网络代理。默认情况下 QNetworkProxy.DefaultProxy is used, which means this socket will query the default proxy settings for the application.
该函数在 Qt 4.1 引入。
另请参阅 setProxy (), QNetworkProxy ,和 QNetworkProxyFactory .
Returns the size of the internal read buffer. This limits the amount of data that the client can receive before you call read () 或 readAll ().
A read buffer size of 0 (the default) means that the buffer has no size limit, ensuring that no data is lost.
另请参阅 setReadBufferSize () and read ().
重实现自 QIODevice.readData ().
重实现自 QIODevice.readLineData ().
Sets the address on the local side of a connection to address .
You can call this function in a subclass of QAbstractSocket to change the return value of the 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 ()).
该函数在 Qt 4.1 引入。
另请参阅 localAddress (), setLocalPort (),和 setPeerAddress ().
Sets the port on the local side of a connection to port .
You can call this function in a subclass of QAbstractSocket to change the return value of the 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 ()).
该函数在 Qt 4.1 引入。
另请参阅 localPort (), localAddress (), setLocalAddress (),和 setPeerPort ().
Sets the address of the remote side of the connection to address .
You can call this function in a subclass of QAbstractSocket to change the return value of the peerAddress () function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.
该函数在 Qt 4.1 引入。
另请参阅 peerAddress (), setPeerPort (),和 setLocalAddress ().
Sets the host name of the remote peer to name .
You can call this function in a subclass of QAbstractSocket to change the return value of the peerName () function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.
该函数在 Qt 4.1 引入。
另请参阅 peerName ().
Sets the port of the remote side of the connection to port .
You can call this function in a subclass of QAbstractSocket to change the return value of the peerPort () function after a connection has been established. This feature is commonly used by proxy connections for virtual connection settings.
该函数在 Qt 4.1 引入。
另请参阅 peerPort (), setPeerAddress (),和 setLocalPort ().
将此套接字的显式网络代理设为 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 .
该函数在 Qt 4.1 引入。
另请参阅 proxy (), QNetworkProxy ,和 QNetworkProxyFactory.queryProxy ().
设置尺寸为 QAbstractSocket 's internal read buffer to be size 字节。
若缓冲尺寸被限制到某个大小, QAbstractSocket won't buffer more than this size of data. Exceptionally, a buffer size of 0 means that the read buffer is unlimited and all incoming data is buffered. This is the default.
This option is useful if you only read the data at certain points in time (e.g., in a real-time streaming application) or if you want to protect your socket against receiving too much data, which may eventually cause your application to run out of memory.
Only QTcpSocket 使用 QAbstractSocket 's internal buffer; 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 QUdpSocket 不起作用。
另请参阅 readBufferSize () 和 read ().
初始化 QAbstractSocket 采用本机套接字描述符 socketDescriptor 。返回 true if socketDescriptor is accepted as a valid socket descriptor; otherwise returns false. The socket is opened in the mode specified by openMode , and enters the socket state 指定通过 socketState .
注意: It is not possible to initialize two abstract sockets with the same native socket descriptor.
另请参阅 socketDescriptor ().
Sets the type of error that last occurred to socketError .
另请参阅 setSocketState () 和 setErrorString ().
设置给定 option 到描述值 value .
该函数在 Qt 4.6 引入。
另请参阅 socketOption ().
把套接字的状态设为 state .
另请参阅 state ().
返回本地套接字描述符为 QAbstractSocket object if this is available; otherwise returns -1.
If the socket is using QNetworkProxy , the returned descriptor may not be usable with native socket functions.
套接字描述符不可用当 QAbstractSocket 是在 UnconnectedState .
另请参阅 setSocketDescriptor ().
返回值,根据 option 选项。
该函数在 Qt 4.6 引入。
另请参阅 setSocketOption ().
返回套接字类型 (TCP、UDP、或其它)。
另请参阅 QTcpSocket and QUdpSocket .
返回套接字的状态。
另请参阅 error ().
重实现自 QIODevice.waitForBytesWritten ().
等待直到套接字被连接,最长 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 error () to determine the cause of the error.
The following example waits up to one second for a connection to be established:
socket->connectToHost("imap", 143); if (socket->waitForConnected(1000)) qDebug("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.
另请参阅 connectToHost () 和 connected ().
等待直到套接字已断开连接,最长 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 error () to determine the cause of the error.
The following example waits up to one second for a connection to be closed:
socket->disconnectFromHost(); if (socket->state() == QAbstractSocket.UnconnectedState || socket->waitForDisconnected(1000)) qDebug("Disconnected!");
若 msecs 为 -1,此函数不会超时。
另请参阅 disconnectFromHost () and close ().
重实现自 QIODevice.waitForReadyRead ().
This function blocks until new data is available for reading and the readyRead() signal has been emitted. The function will timeout after msecs 毫秒;默认超时是 30000 毫秒。
The function returns true if the readyRead () signal is emitted and there is new data available for reading; otherwise it returns false (若发生错误或操作超时)。
另请参阅 waitForBytesWritten ().
重实现自 QIODevice.writeData ().
This is the default overload of this signal.
此信号被发射在 connectToHost () has been called and a connection has been successfully established.
注意: On some operating systems the connected() signal may be directly emitted from the connectToHost () call for connections to the localhost.
另请参阅 connectToHost () 和 disconnected ().
This is the default overload of this signal.
This signal is emitted when the socket has been disconnected.
警告: 若需要删除 sender () of this signal in a slot connected to it, use the deleteLater() 函数。
另请参阅 connectToHost (), disconnectFromHost (), and abort ().
This is the default overload of this signal.
此信号被发射在发生错误之后。 socketError parameter describes the type of error that occurred.
QAbstractSocket.SocketError is not a registered metatype, so for queued connections, you will have to register it with Q_DECLARE_METATYPE () 和 qRegisterMetaType ().
另请参阅 error (), errorString (),和 创建自定义 Qt 类型 .
This is the default overload of this signal.
此信号被发射在 connectToHost () has been called and the host lookup has succeeded.
注意: Since Qt 4.6.3 QAbstractSocket may emit hostFound() directly from the connectToHost () call since a DNS result could have been cached.
另请参阅 connected ().
This is the default overload of this signal.
此信号可以被发射当 proxy that requires authentication is used. The authenticator object can then be filled in with the required details to allow authentication and continue the connection.
注意: It is not possible to use a QueuedConnection to connect to this signal, as the connection will fail if the authenticator has not been filled in with new information when the signal returns.
该函数在 Qt 4.3 引入。
另请参阅 QAuthenticator and QNetworkProxy .
This is the default overload of this signal.
此信号被发射每当 QAbstractSocket 的状态改变。 socketState 参数是新状态。
QAbstractSocket.SocketState is not a registered metatype, so for queued connections, you will have to register it with Q_REGISTER_METATYPE() and qRegisterMetaType ().
另请参阅 state () and 创建自定义 Qt 类型 .