Qt源码分析--QAbstractSocket类

QAbstractSocket类的头文件通常包含了一些重要的成员函数、信号和槽以及一些常量定义。

  1. 成员函数:
  • connectToHost():用于与指定的主机和端口建立连接。
  • writeData():向套接字写入数据。
  • readData():从套接字读取数据。
  • disconnectFromHost():关闭套接字连接。
  • error():返回套接字的错误状态。
  1. 信号和槽:
  • connected():在套接字成功连接到主机时触发的信号。
  • readyRead():当套接字有可读数据时触发的信号。
  • error():在套接字发生错误时触发的信号。
  1. 常量定义:
  • ConnectedState:表示套接字已连接的状态。
  • UnconnectedState:表示套接字未连接的状态。
  • HostLookupState:表示套接字正在进行主机查找的状态。

QAbstractSocket类是一个抽象类,不能直接实例化,而是通过其具体子类(如QTcpSocket和QUdpSocket)来使用。它提供了一组通用的接口和功能,用于处理网络通信和数据传输。

1.connectToHost

设置套接字的参数并发起与指定主机和端口的连接操作。

void QAbstractSocket::connectToHost(const QString &hostName, quint16 port,
                                    OpenMode openMode,
                                    NetworkLayerProtocol protocol)
{
    Q_D(QAbstractSocket);
#if defined(QABSTRACTSOCKET_DEBUG)
    qDebug("QAbstractSocket::connectToHost(\"%s\", %i, %i)...", qPrintable(hostName), port,
           (int) openMode);
#endif
    if (d->state == ConnectedState || d->state == ConnectingState
        || d->state == ClosingState || d->state == HostLookupState) {
        qWarning("QAbstractSocket::connectToHost() called when already looking up or connecting/connected to \"%s\"", qPrintable(hostName));
        d->setErrorAndEmit(OperationError, tr("Trying to connect while connection is in progress"));
        return;
    }
    d->preferredNetworkLayerProtocol = protocol;
    d->hostName = hostName;
    d->port = port;
    d->setReadChannelCount(0);
    d->setWriteChannelCount(0);
    d->abortCalled = false;
    d->pendingClose = false;
    if (d->state != BoundState) {
        d->state = UnconnectedState;
        d->localPort = 0;
        d->localAddress.clear();
    }
    d->peerPort = 0;
    d->peerAddress.clear();
    d->peerName = hostName;
    if (d->hostLookupId != -1) {
        QHostInfo::abortHostLookup(d->hostLookupId);
        d->hostLookupId = -1;
    }
#ifndef QT_NO_NETWORKPROXY
    // Get the proxy information
    d->resolveProxy(hostName, port);
    if (d->proxyInUse.type() == QNetworkProxy::DefaultProxy) {
        // failed to setup the proxy
        d->setErrorAndEmit(UnsupportedSocketOperationError,
                           tr("Operation on socket is not supported"));
        return;
    }
#endif
    // Sync up with error string, which open() shall clear.
    d->socketError = UnknownSocketError;
    if (openMode & QIODevice::Unbuffered)
        d->isBuffered = false;
    else if (!d_func()->isBuffered)
        openMode |= QAbstractSocket::Unbuffered;
    QIODevice::open(openMode);
    d->readChannelCount = d->writeChannelCount = 0;
#ifndef Q_OS_WINRT
    d->state = HostLookupState;
    emit stateChanged(d->state);
    QHostAddress temp;
    if (temp.setAddress(hostName)) {
        QHostInfo info;
        info.setAddresses(QList() << temp

你可能感兴趣的:(Qt,源码分析,网络,服务器,linux)