QAbstractSocket Class

The QAbstractSocket class provides the base functionality common to all socket types. 更多...

头文件: #include <QAbstractSocket>
qmake: QT += network
基类: QIODevice
派生类:

QTcpSocket and QUdpSocket

Note: All functions in this class are reentrant.

公有类型

enum BindFlag { ShareAddress, DontShareAddress, ReuseAddressHint, DefaultForPlatform }
flags BindMode
enum NetworkLayerProtocol { IPv4Protocol, IPv6Protocol, AnyIPProtocol, UnknownNetworkLayerProtocol }
enum PauseMode { PauseNever, PauseOnSslErrors }
flags PauseModes
enum SocketError { ConnectionRefusedError, RemoteHostClosedError, HostNotFoundError, SocketAccessError, ..., UnknownSocketError }
enum SocketOption { LowDelayOption, KeepAliveOption, MulticastTtlOption, MulticastLoopbackOption, ..., ReceiveBufferSizeSocketOption }
enum SocketState { UnconnectedState, HostLookupState, ConnectingState, ConnectedState, ..., ListeningState }
enum SocketType { TcpSocket, UdpSocket, SctpSocket, UnknownSocketType }

公有函数

QAbstractSocket(SocketType socketType, QObject *parent)
virtual ~QAbstractSocket()
void abort()
bool bind(const QHostAddress &address, quint16 port = 0, BindMode mode = DefaultForPlatform)
bool bind(quint16 port = 0, BindMode mode = DefaultForPlatform)
virtual void connectToHost(const QString &hostName, quint16 port, OpenMode openMode = ReadWrite, NetworkLayerProtocol protocol = AnyIPProtocol)
virtual void connectToHost(const QHostAddress &address, quint16 port, OpenMode openMode = ReadWrite)
virtual void disconnectFromHost()
SocketError error() const
bool flush()
bool isValid() const
QHostAddress localAddress() const
quint16 localPort() const
PauseModes pauseMode() const
QHostAddress peerAddress() const
QString peerName() const
quint16 peerPort() const
QNetworkProxy proxy() const
qint64 readBufferSize() const
virtual void resume()
void setPauseMode(PauseModes pauseMode)
void setProxy(const QNetworkProxy &networkProxy)
virtual void setReadBufferSize(qint64 size)
virtual bool setSocketDescriptor(qintptr socketDescriptor, SocketState socketState = ConnectedState, OpenMode openMode = ReadWrite)
virtual void setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
virtual qintptr socketDescriptor() const
virtual QVariant socketOption(QAbstractSocket::SocketOption option)
SocketType socketType() const
SocketState state() const
virtual bool waitForConnected(int msecs = 30000)
virtual bool waitForDisconnected(int msecs = 30000)

重新实现的公有函数

virtual bool atEnd() const
virtual qint64 bytesAvailable() const
virtual qint64 bytesToWrite() const
virtual bool canReadLine() const
virtual void close()
virtual bool isSequential() const
virtual bool waitForBytesWritten(int msecs = 30000)
virtual bool waitForReadyRead(int msecs = 30000)

信号

void connected()
void disconnected()
void error(QAbstractSocket::SocketError socketError)
void hostFound()
void proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
void stateChanged(QAbstractSocket::SocketState socketState)

受保护的函数

void setLocalAddress(const QHostAddress &address)
void setLocalPort(quint16 port)
void setPeerAddress(const QHostAddress &address)
void setPeerName(const QString &name)
void setPeerPort(quint16 port)
void setSocketError(SocketError socketError)
void setSocketState(SocketState state)

重新实现的受保护函数

virtual qint64 readData(char *data, qint64 maxSize)
virtual qint64 readLineData(char *data, qint64 maxlen)
virtual qint64 writeData(const char *data, qint64 size)
  • 5 个受保护的函数继承自 QIODevice
  • 9 个受保护的函数继承自 QObject

其他继承的成员

  • 1 个属性继承自 QObject
  • 1 个公有槽函数继承自 QObject
  • 1 个公有变量继承自 QObject
  • 10 个静态公有成员继承自 QObject
  • 2 个受保护的变量继承自 QObject

详细描述

QAbstractSocket 类为所有的socket通信类提供了最基本的功能.

QAbstractSocketQTcpSocketQUdpSocket 的基类, 包含了这两个类所有的常规功能. 如果你需要一个 socket, 那么你需要两个步骤:

TCP (Transmission Control Protocol) 是一种可靠的, 面向流, 面向连接的传输协议. UDP (User Datagram Protocol) 是一种不可靠的, 面向数据报的无连接协议. 实际上, 这意味着 TCP 更适合于连续数据传输, 而当可靠性不重要时, 可以使用更轻量的UDP.

QAbstractSocket 的 API 统一了这两种协议之间的大部分差异. 例如, 尽管 UDP 是无连接的, 但 connectToHost() 为 UDP 套接字建立了虚拟连接, 使您可以忽略底层协议, 以几乎相同的方式使用 QAbstractSocket. 在内部, QAbstractSocket 记录了传递给 connectToHost() 的地址和端口, 并且能在调用 read() 和 write() 之类的成员函数时使用这些值.

任何情况下, QAbstractSocket 都有一个状态 (由 state() 返回). 初始状态为 UnconnectedState. 调用 connectToHost(), socket 首先进入 HostLookupState. 如果找到了主机, 则 QAbstractSocket 进入 ConnectingState 状态, 并发送 hostFound() 信号. 建立连接后, 它将进入 ConnectedState 状态, 并发送 connected() 信号. 如果在以上列出任何阶段发生了错误, 则会发出 error() 信号. 每当状态发生更改时, QAbstractSocket 会发出 stateChanged() 信号. 方便起见, 当 socket 已准备好进行读取和写入数据操作时, isValid() 返回 true, 但是要注意一下, 在进行读写操作之前, socket 的状态必须为 ConnectedState 状态.

你可以通过调用 read() 或 write() 进行数据读写操作, 同时为了方便特殊的数据读入操作, 你还可以使用 readLine() 和 readAll(). 当你需要以字节为单位进行数据读写操作时,可以使用 QAbstractSocket 的父类QIODevice提供的成员函数 getChar(), putChar(), ungetChar(). 待数据写入 socket 后, QAbstractSocket 会发出继承自父类QIODevice的信号 bytesWritten(). 注意: Qt并不限制写缓冲区的大小. 你可以通过监听 bytesWritten() 信号来监视其大小.

每当有新的数据块到达时, QAbstractSocket 都会发出继承自父类 QIODevicereadyRead() 信号. 你可以通过 bytesAvailable() 获得当前读取缓冲区中可读取的字节数. 通常来讲, 你可以将 readyRead() 信号与一个槽函数相连接, 然后在该槽函数中读取所有可用的数据. 如果你不一次性读取所有数据, 则其余数据以后仍可以读取. 并且任何新的传入数据都将追加到 QAbstractSocket 的内部读取缓冲区中. 你可以调用 setReadBufferSize() 限制读取缓冲区的大小.

你可以调用 disconnectFromHost() 关闭 socket, QAbstractSocket 会进入 QAbstractSocket::ClosingState. 待所有未处理数据写入 socket 后, QAbstractSocket 将关闭 socket, 进入 QAbstractSocket::UnconnectedState, 并发送 disconnected() 信号. 如果要立即中止连接, 并丢弃所有未处理数据, 请调用 abort(). 如果远程主机关闭了该连接, QAbstractSocket 将发出(QAbstractSocket::RemoteHostClosedError)错误信号, 在此期间 socket 状态仍为 ConnectedState 状态, 此后将发送 disconnected() 信号.

你可以调用 peerPort() 和 peerAddress() 获取已连接的对等方的端口和地址. peerName() 返回传递给 connectToHost() 的对等方的主机名. localPort() 和 localAddress() 返回本地套接字的端口和地址.

QAbstractSocket提供了一组函数, 这些函数可以挂起调用线程, 直到发出某些信号为止. 这些函数可用于实现阻塞 socket:

示例:


      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, 则说明连接已关闭或发生了错误.

使用阻塞 socket 编程与使用非阻塞 socket 编程完全不同. 阻塞 socket 不需要有一个事件循环, 这通常可以简化代码. 但是, 在GUI应用程序中, 阻塞 socket 只能在非GUI线程中使用, 以避免冻结用户界面. 有关这两种方法的概述, 参见 fortuneclientblockingfortuneclient.

注意: Qt官方并不推荐将阻塞函数与信号一起使用.

QAbstractSocket 可以与 QTextStreamQDataStream 的流运算符 (operator<<() 和 operator>>()) 一起使用. 但是, 有一个问题需要注意: 在尝试使用 operator>>() 读取数据之前, 必须确保有足够的数据可用.

参见 QNetworkAccessManagerQTcpServer.

成员类型

enum QAbstractSocket::BindFlag
flags QAbstractSocket::BindMode

这个枚举描述了一些不同的标志, 这些标志可以传递为 QAbstractSocket::bind()的参数, 指定了不同的主机绑定模式.

ConstantValueDescription
QAbstractSocket::ShareAddress0x1允许其他服务绑定到相同的地址和端口. 在多个进程通过侦听相同的地址和端口来分担单个服务的负载的情况下(例如., 具有多个预分支侦听器的Web服务器可以大大缩短响应时间), 该模式十分有效. 但是, 由于该模式下允许任何服务对主机进行重新绑定, 因此此选项存在着安全隐患. 请注意, 你还可以允许你的服务重新绑定现有的共享地址通过将此选项与 ReuseAddressHint 结合使用. 在 Unix 上, 这等效于 SO_REUSEADDR 套接字选项. 在 Windows 上, 这是默认行为, 因此将忽略此选项.
QAbstractSocket::DontShareAddress0x2绑定主机时独占地址和端口, 不允许其他服务重新绑定. 将此选项作为 QAbstractSocket::bind 参数, 可以确保在绑定主机成功后, 你当前的服务是唯一侦听指定地址和端口的服务. 即使其他服务通过指定 ReuseAddressHint 模式来绑定服务, 这个操作也是不允许的. 该模式相比 ShareAddress 提供了更高的安全性, 但是在某些操作系统上, 它要求您以管理员权限运行该服务. 在 Unix 和 macOS 上, 独占地址和端口是绑定主机的默认行为, 因此该选项将被忽略. 在 Windows 上, 此选项使用 SO_EXCLUSIVEADDRUSE socket 选项.
QAbstractSocket::ReuseAddressHint0x4示意 QAbstractSocket 即使地址和端口已被另一个套接字绑定, 它也应尝试重新绑定服务. 在 Windows 和 Unix 上, 这等效于 SO_REUSEADDR socket 选项.
QAbstractSocket::DefaultForPlatform0x0使用当前平台的默认模式. 在 Unix 和 macOS 上, 这等效于( DontShareAddress + ReuseAddressHint). 在 Windows 上, 它等效于 ShareAddress.

This enum was introduced or modified in Qt 5.0.

BindMode 类型是 QFlags<BindFlag> 生成的用户自定义类型. 它存储着 BindFlag 值的 OR 组合.

enum QAbstractSocket::NetworkLayerProtocol

该枚举描述了Qt中可以使用的网络层协议.

ConstantValueDescription
QAbstractSocket::IPv4Protocol0IPv4
QAbstractSocket::IPv6Protocol1IPv6
QAbstractSocket::AnyIPProtocol2IPv4 或 IPv6
QAbstractSocket::UnknownNetworkLayerProtocol-1除 IPv4 和 IPv6 之外的协议

参见 QHostAddress::protocol().

enum QAbstractSocket::PauseMode
flags QAbstractSocket::PauseModes

该枚举描述了套接字在什么情况下该停止传输中的数据. 当前Qt支持的唯一通知是 QSslSocket::sslErrors().

ConstantValueDescription
QAbstractSocket::PauseNever0x0永远不暂停 socket 的数据传输. 该模式是默认设置, 符合Qt 4的标准.
QAbstractSocket::PauseOnSslErrors0x1收到 SSL 错误(即. QSslSocket::sslErrors() ) 的通知后, 暂停 socket 的数据传输.

This enum was introduced or modified in Qt 5.0.

PauseModes 类型是 QFlags<PauseMode> 生成的用户自定义类型. 它储存着 PauseMode 值的 OR 组合.

enum QAbstractSocket::SocketError

该枚举描述了常见的套接字错误.

ConstantValueDescription
QAbstractSocket::ConnectionRefusedError0连接被对方拒绝(或连接超时).
QAbstractSocket::RemoteHostClosedError1远程主机关闭了连接. 注意, 在发送远程主机连接关闭的通知后, 客户端 socket (即., 这个socket)将被关闭.
QAbstractSocket::HostNotFoundError2未能找到主机地址.
QAbstractSocket::SocketAccessError3程序没有权限来进行特定的 socket 操作.
QAbstractSocket::SocketResourceError4本地系统资源不足(例如., 本地系统使用了过多的套接字).
QAbstractSocket::SocketTimeoutError5socket 操作超时.
QAbstractSocket::DatagramTooLargeError6数据报大于操作系统的限制(该限制可以低至8192字节).
QAbstractSocket::NetworkError7网络发生错误(例如., 网线断开).
QAbstractSocket::AddressInUseError8QAbstractSocket::bind() 指定的主机地址已被另一个 socket 使用独占模式绑定.
QAbstractSocket::SocketAddressNotAvailableError9 QAbstractSocket::bind() 指定的主机地址不属于主机.
QAbstractSocket::UnsupportedSocketOperationError10本地操作系统不支持请求的 socket 操作 (例如., 缺少IPv6支持).
QAbstractSocket::ProxyAuthenticationRequiredError12socket 正在使用代理, 并且代理需要身份验证.
QAbstractSocket::SslHandshakeFailedError13SSL / TLS 握手失败, 因此连接已关闭(仅在 QSslSocket 中使用)
QAbstractSocket::UnfinishedSocketOperationError11仅由 QAbstractSocketEngine 使用, 上一次尝试的操作尚未完成(仍在后台进行).
QAbstractSocket::ProxyConnectionRefusedError14代理服务器拒绝了连接
QAbstractSocket::ProxyConnectionClosedError15与代理服务器的连接意外关闭(在建立与对方的最终连接之前)
QAbstractSocket::ProxyConnectionTimeoutError16与代理服务器的连接超时或代理服务器在身份验证阶段停止响应.
QAbstractSocket::ProxyNotFoundError17找不到使用 setProxy() (或应用程序代理)设置的代理地址.
QAbstractSocket::ProxyProtocolError18与代理服务器通信失败, 因为无法理解来自代理服务器的响应, 这通常是代理服务协议错误造成的.
QAbstractSocket::OperationError19所处的状态不允许该操作 socket 所处的状态不允许该操作.
QAbstractSocket::SslInternalError20使用的 SSL 库出现内部错误. 这可能是由于 SSL 库安装错误或配置错误造成的.
QAbstractSocket::SslInvalidUserDataError21提供了无效的数据(证书, 密钥, 密码等), 其使用导致 SSL 库出现错误.
QAbstractSocket::TemporaryError22发生临时错误(例如., 操作将阻塞socket, 而 socket 未阻塞).
QAbstractSocket::UnknownSocketError-1出现了一个未知错误.

参见 QAbstractSocket::error().

enum QAbstractSocket::SocketOption

该枚举表示可以在 socket 上设置的选项. 如果需要设置这些选项, 你可以在 socket 接收到 connected() 信号之后, 或者在 QTcpServer 接收到新的 socket 之后, 对它们进行设置.

ConstantValueDescription
QAbstractSocket::LowDelayOption0尝试优化套接字以降低延迟. 对于 QTcpSocket, 这将设置 TCP_NODELAY 选项并禁用 Nagle 的算法. 将此设置为1启用.
QAbstractSocket::KeepAliveOption1将此设置为1以启用 SO_KEEPALIVE socket 选项
QAbstractSocket::MulticastTtlOption2将此设置为整数值以设置 IP_MULTICAST_TTL ( 多播数据报的 TTL ) socket 选项.
QAbstractSocket::MulticastLoopbackOption3将此设置为1以启用 IP_MULTICAST_LOOP (多播环回) socket 选项.
QAbstractSocket::TypeOfServiceOption4Windows 不支持此选项. 这映射到IP_TOS socket 选项. 有关其可能的可取值, 请参见下表.
QAbstractSocket::SendBufferSizeSocketOption5在操作系统级别设置 socket 发送缓冲区的大小(以字节为单位). 这映射到 SO_SNDBUF socket 选项. 该选项不会影响 QIODevice or QAbstractSocket 缓冲区. 这个枚举值在 Qt 5.3 中引入
QAbstractSocket::ReceiveBufferSizeSocketOption6在操作系统级别设置套接字接收缓冲区的大小(以字节为单位). 这映射到 SO_RCVBUF 套接字选项. 此选项不会影响 QIODeviceQAbstractSocket 缓冲区 (参见 setReadBufferSize()). 这个枚举值已在Qt 5.3 中引入.
QAbstractSocket::PathMtuSocketOption7检索IP堆栈当前已知的路径最大传输单位(PMTU )值(如果该值存在). 一些IP堆栈还允许设置 MTU 进行传输. 这个枚举值在Qt 5.11中引入.

TypeOfServiceOption 可能的可取值(优先级):

ValueDescription
224Network control
192Internetwork control
160CRITIC/ECP
128Flash override
96Flash
64Immediate
32Priority
0Routine

This enum was introduced or modified in Qt 4.6.

参见 QAbstractSocket::setSocketOption() 和 QAbstractSocket::socketOption().

enum QAbstractSocket::SocketState

This enum describes the different states in which a socket can be.

ConstantValueDescription
QAbstractSocket::UnconnectedState0socket 未连接.
QAbstractSocket::HostLookupState1socket 正在查询主机.
QAbstractSocket::ConnectingState2socket 开始建立连接.
QAbstractSocket::ConnectedState3新的连接已建立.
QAbstractSocket::BoundState4socket 已绑定到一个地址和端口.
QAbstractSocket::ClosingState6socket 即将关闭(数据可能仍在等待写入).
QAbstractSocket::ListeningState5socket 仅限内部使用.

参见 QAbstractSocket::state().

enum QAbstractSocket::SocketType

This enum describes the transport layer protocol.

ConstantValueDescription
QAbstractSocket::TcpSocket0TCP
QAbstractSocket::UdpSocket1UDP
QAbstractSocket::SctpSocket2SCTP
QAbstractSocket::UnknownSocketType-1除 TCP, UDP 和 SCTP 外的协议

参见 QAbstractSocket::socketType().

成员函数

QAbstractSocket::QAbstractSocket(SocketType socketType, QObject *parent)

Creates a new abstract socket of type socketType. The parent argument is passed to QObject's constructor.

参见 socketType(), QTcpSocket, and QUdpSocket.

[virtual] QAbstractSocket::~QAbstractSocket()

Destroys the socket.

void QAbstractSocket::abort()

Aborts the current connection and resets the socket. Unlike disconnectFromHost(), this function immediately closes the socket, discarding any pending data in the write buffer.

参见 disconnectFromHost() and close().

[virtual] bool QAbstractSocket::atEnd() const

Reimplemented from 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() and readyRead().

bool QAbstractSocket::bind(const QHostAddress &address, quint16 port = 0, BindMode mode = DefaultForPlatform)

Binds to address on port port, using the BindMode mode.

Binds this socket to the address address and the port port.

For UDP sockets, after binding, the signal QUdpSocket::readyRead() is emitted whenever a UDP datagram arrives on the specified address and port. Thus, This function is useful to write UDP servers.

For TCP sockets, this function may be used to specify which interface to use for an outgoing connection, which is useful in case of multiple network interfaces.

By default, the socket is bound using the DefaultForPlatform BindMode. If a port is not specified, a random port is chosen.

On success, the functions returns true and the socket enters BoundState; otherwise it returns false.

This function was introduced in Qt 5.0.

bool QAbstractSocket::bind(quint16 port = 0, BindMode mode = DefaultForPlatform)

This is an overloaded function.

Binds to QHostAddress:Any on port port, using the BindMode mode.

By default, the socket is bound using the DefaultForPlatform BindMode. If a port is not specified, a random port is chosen.

This function was introduced in Qt 5.0.

[virtual] qint64 QAbstractSocket::bytesAvailable() const

Reimplemented from QIODevice::bytesAvailable().

Returns the number of incoming bytes that are waiting to be read.

参见 bytesToWrite() and read().

[virtual] qint64 QAbstractSocket::bytesToWrite() const

Reimplemented from 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() is called.

参见 bytesAvailable() and flush().

[virtual] bool QAbstractSocket::canReadLine() const

Reimplemented from QIODevice::canReadLine().

Returns true if a line of data can be read from the socket; otherwise returns false.

参见 readLine().

[virtual] void QAbstractSocket::close()

Reimplemented from QIODevice::close().

Closes the I/O device for the socket and calls disconnectFromHost() to close the socket's connection.

See QIODevice::close() for a description of the actions that occur when an I/O device is closed.

参见 abort().

[virtual] void QAbstractSocket::connectToHost(const QString &hostName, quint16 port, OpenMode openMode = ReadWrite, NetworkLayerProtocol protocol = AnyIPProtocol)

Attempts to make a connection to hostName on the given port. The protocol parameter can be used to specify which network protocol to use (eg. IPv4 or IPv6).

The socket is opened in the given openMode and first enters HostLookupState, then performs a host name lookup of hostName. If the lookup succeeds, hostFound() is emitted and QAbstractSocket enters ConnectingState. It then attempts to connect to the address or addresses returned by the lookup. Finally, if a connection is established, QAbstractSocket enters ConnectedState and emits 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(), and waitForConnected().

[virtual] void QAbstractSocket::connectToHost(const QHostAddress &address, quint16 port, OpenMode openMode = ReadWrite)

This is an overloaded function.

Attempts to make a connection to address on port port.

[signal] void QAbstractSocket::connected()

This signal is emitted after connectToHost() has been called and a connection has been successfully established.

Note: On some operating systems the connected() signal may be directly emitted from the connectToHost() call for connections to the localhost.

参见 connectToHost() and disconnected().

[virtual] void QAbstractSocket::disconnectFromHost()

Attempts to close the socket. If there is pending data waiting to be written, QAbstractSocket will enter ClosingState and wait until all data has been written. Eventually, it will enter UnconnectedState and emit the disconnected() signal.

参见 connectToHost().

[signal] void QAbstractSocket::disconnected()

This signal is emitted when the socket has been disconnected.

Warning: If you need to delete the sender() of this signal in a slot connected to it, use the deleteLater() function.

参见 connectToHost(), disconnectFromHost(), and abort().

SocketError QAbstractSocket::error() const

Returns the type of error that last occurred.

参见 state() and errorString().

[signal] void QAbstractSocket::error(QAbstractSocket::SocketError socketError)

This signal is emitted after an error occurred. The socketError parameter describes the type of error that occurred.

When this signal is emitted, the socket may not be ready for a reconnect attempt. In that case, attempts to reconnect should be done from the event loop. For example, use a QTimer::singleShot() with 0 as the timeout.

QAbstractSocket::SocketError is not a registered metatype, so for queued connections, you will have to register it with Q_DECLARE_METATYPE() and qRegisterMetaType().

Note: Signal error is overloaded in this class. To connect to this one using the function pointer syntax, you must specify the signal type in a static cast, as shown in this example:


  connect(abstractSocket, static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error),
      [=](QAbstractSocket::SocketError socketError){ /* ... */ });

参见 error(), errorString(), and Creating Custom Qt Types.

bool QAbstractSocket::flush()

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.

Call this function if you need 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() instead.

参见 write() and waitForBytesWritten().

[signal] void QAbstractSocket::hostFound()

This signal is emitted after connectToHost() has been called and the host lookup has succeeded.

Note: Since Qt 4.6.3 QAbstractSocket may emit hostFound() directly from the connectToHost() call since a DNS result could have been cached.

参见 connected().

[virtual] bool QAbstractSocket::isSequential() const

Reimplemented from QIODevice::isSequential().

bool QAbstractSocket::isValid() const

Returns true if the socket is valid and ready for use; otherwise returns false.

Note: The socket's state must be ConnectedState before reading and writing can occur.

参见 state().

QHostAddress QAbstractSocket::localAddress() const

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(), and setLocalAddress().

quint16 QAbstractSocket::localPort() const

Returns the host port number (in native byte order) of the local socket if available; otherwise returns 0.

参见 localAddress(), peerPort(), and setLocalPort().

PauseModes QAbstractSocket::pauseMode() const

Returns the pause mode of this socket.

This function was introduced in Qt 5.0.

参见 setPauseMode() and resume().

QHostAddress QAbstractSocket::peerAddress() const

Returns the address of the connected peer if the socket is in ConnectedState; otherwise returns QHostAddress::Null.

参见 peerName(), peerPort(), localAddress(), and setPeerAddress().

QString QAbstractSocket::peerName() const

Returns the name of the peer as specified by connectToHost(), or an empty QString if connectToHost() has not been called.

参见 peerAddress(), peerPort(), and setPeerName().

quint16 QAbstractSocket::peerPort() const

Returns the port of the connected peer if the socket is in ConnectedState; otherwise returns 0.

参见 peerAddress(), localPort(), and setPeerPort().

QNetworkProxy QAbstractSocket::proxy() const

Returns the network proxy for this socket. By default QNetworkProxy::DefaultProxy is used, which means this socket will query the default proxy settings for the application.

This function was introduced in Qt 4.1.

参见 setProxy(), QNetworkProxy, and QNetworkProxyFactory.

[signal] void QAbstractSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)

This signal can be emitted when a 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.

Note: 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.

This function was introduced in Qt 4.3.

参见 QAuthenticator and QNetworkProxy.

qint64 QAbstractSocket::readBufferSize() const

Returns the size of the internal read buffer. This limits the amount of data that the client can receive before you call read() or 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().

[virtual protected] qint64 QAbstractSocket::readData(char *data, qint64 maxSize)

Reimplemented from QIODevice::readData().

[virtual protected] qint64 QAbstractSocket::readLineData(char *data, qint64 maxlen)

Reimplemented from QIODevice::readLineData().

[virtual] void QAbstractSocket::resume()

Continues data transfer on the socket. This method should only be used after the socket has been set to pause upon notifications and a notification has been received. The only notification currently supported is QSslSocket::sslErrors(). Calling this method if the socket is not paused results in undefined behavior.

This function was introduced in Qt 5.0.

参见 pauseMode() and setPauseMode().

[protected] void QAbstractSocket::setLocalAddress(const QHostAddress &address)

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., QAbstractSocket::bind()).

This function was introduced in Qt 4.1.

参见 localAddress(), setLocalPort(), and setPeerAddress().

[protected] void QAbstractSocket::setLocalPort(quint16 port)

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., QAbstractSocket::bind()).

This function was introduced in Qt 4.1.

参见 localPort(), localAddress(), setLocalAddress(), and setPeerPort().

void QAbstractSocket::setPauseMode(PauseModes pauseMode)

Controls whether to pause upon receiving a notification. The pauseMode parameter specifies the conditions in which the socket should be paused. The only notification currently supported is QSslSocket::sslErrors(). If set to PauseOnSslErrors, data transfer on the socket will be paused and needs to be enabled explicitly again by calling resume(). By default this option is set to PauseNever. This option must be called before connecting to the server, otherwise it will result in undefined behavior.

This function was introduced in Qt 5.0.

参见 pauseMode() and resume().

[protected] void QAbstractSocket::setPeerAddress(const QHostAddress &address)

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.

This function was introduced in Qt 4.1.

参见 peerAddress(), setPeerPort(), and setLocalAddress().

[protected] void QAbstractSocket::setPeerName(const QString &name)

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.

This function was introduced in Qt 4.1.

参见 peerName().

[protected] void QAbstractSocket::setPeerPort(quint16 port)

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.

This function was introduced in Qt 4.1.

参见 peerPort(), setPeerAddress(), and setLocalPort().

void QAbstractSocket::setProxy(const QNetworkProxy &networkProxy)

Sets the explicit network proxy for this socket to networkProxy.

To disable the use of a proxy for this socket, use the QNetworkProxy::NoProxy proxy type:


  socket->setProxy(QNetworkProxy::NoProxy);

The default value for the proxy is 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.

This function was introduced in Qt 4.1.

参见 proxy(), QNetworkProxy, and QNetworkProxyFactory::queryProxy().

[virtual] void QAbstractSocket::setReadBufferSize(qint64 size)

Sets the size of QAbstractSocket's internal read buffer to be size bytes.

If the buffer size is limited to a certain 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 uses 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 has no effect.

参见 readBufferSize() and read().

[virtual] bool QAbstractSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState socketState = ConnectedState, OpenMode openMode = ReadWrite)

Initializes QAbstractSocket with the native socket descriptor socketDescriptor. Returns 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 specified by socketState. Read and write buffers are cleared, discarding any pending data.

Note: It is not possible to initialize two abstract sockets with the same native socket descriptor.

参见 socketDescriptor().

[protected] void QAbstractSocket::setSocketError(SocketError socketError)

Sets the type of error that last occurred to socketError.

参见 setSocketState() and setErrorString().

[virtual] void QAbstractSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)

Sets the given option to the value described by value.

Note: On Windows Runtime, QAbstractSocket::KeepAliveOption must be set before the socket is connected.

This function was introduced in Qt 4.6.

参见 socketOption().

[protected] void QAbstractSocket::setSocketState(SocketState state)

Sets the state of the socket to state.

参见 state().

[virtual] qintptr QAbstractSocket::socketDescriptor() const

Returns the native socket descriptor of the 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.

The socket descriptor is not available when QAbstractSocket is in UnconnectedState.

参见 setSocketDescriptor().

[virtual] QVariant QAbstractSocket::socketOption(QAbstractSocket::SocketOption option)

Returns the value of the option option.

This function was introduced in Qt 4.6.

参见 setSocketOption().

SocketType QAbstractSocket::socketType() const

Returns the socket type (TCP, UDP, or other).

参见 QTcpSocket and QUdpSocket.

SocketState QAbstractSocket::state() const

Returns the state of the socket.

参见 error().

[signal] void QAbstractSocket::stateChanged(QAbstractSocket::SocketState socketState)

This signal is emitted whenever QAbstractSocket's state changes. The socketState parameter is the new state.

QAbstractSocket::SocketState is not a registered metatype, so for queued connections, you will have to register it with Q_DECLARE_METATYPE() and qRegisterMetaType().

参见 state() and Creating Custom Qt Types.

[virtual] bool QAbstractSocket::waitForBytesWritten(int msecs = 30000)

Reimplemented from QIODevice::waitForBytesWritten().

This function blocks until at least one byte has been written on the socket and the bytesWritten() signal has been emitted. The function will timeout after msecs milliseconds; the default timeout is 30000 milliseconds.

The function returns true if the bytesWritten() signal is emitted; otherwise it returns false (if an error occurred or the operation timed out).

Note: This function may fail randomly on Windows. Consider using the event loop and the bytesWritten() signal if your software will run on Windows.

参见 waitForReadyRead().

[virtual] bool QAbstractSocket::waitForConnected(int msecs = 30000)

Waits until the socket is connected, up to 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!");

If msecs is -1, this function will not time out.

Note: This function may wait slightly longer than msecs, depending on the time it takes to complete the host lookup.

Note: Multiple calls to this functions do not accumulate the time. If the function times out, the connecting process will be aborted.

Note: This function may fail randomly on Windows. Consider using the event loop and the connected() signal if your software will run on Windows.

参见 connectToHost() and connected().

[virtual] bool QAbstractSocket::waitForDisconnected(int msecs = 30000)

Waits until the socket has disconnected, up to 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!");

If msecs is -1, this function will not time out.

Note: This function may fail randomly on Windows. Consider using the event loop and the disconnected() signal if your software will run on Windows.

参见 disconnectFromHost() and close().

[virtual] bool QAbstractSocket::waitForReadyRead(int msecs = 30000)

Reimplemented from 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 milliseconds; the default timeout is 30000 milliseconds.

The function returns true if the readyRead() signal is emitted and there is new data available for reading; otherwise it returns false (if an error occurred or the operation timed out).

Note: This function may fail randomly on Windows. Consider using the event loop and the readyRead() signal if your software will run on Windows.

参见 waitForBytesWritten().

[virtual protected] qint64 QAbstractSocket::writeData(const char *data, qint64 size)

Reimplemented from QIODevice::writeData().