⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 qnativesocketengine.cpp

📁 奇趣公司比较新的qt/emd版本
💻 CPP
📖 第 1 页 / 共 3 页
字号:
/******************************************************************************** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.**** This file is part of the QtNetwork module of the Qt Toolkit.**** This file may be used under the terms of the GNU General Public** License version 2.0 as published by the Free Software Foundation** and appearing in the file LICENSE.GPL included in the packaging of** this file.  Please review the following information to ensure GNU** General Public Licensing requirements will be met:** http://trolltech.com/products/qt/licenses/licensing/opensource/**** If you are unsure which license is appropriate for your use, please** review the following information:** http://trolltech.com/products/qt/licenses/licensing/licensingoverview** or contact the sales department at sales@trolltech.com.**** In addition, as a special exception, Trolltech gives you certain** additional rights. These rights are described in the Trolltech GPL** Exception version 1.0, which can be found at** http://www.trolltech.com/products/qt/gplexception/ and in the file** GPL_EXCEPTION.txt in this package.**** In addition, as a special exception, Trolltech, as the sole copyright** holder for Qt Designer, grants users of the Qt/Eclipse Integration** plug-in the right for the Qt/Eclipse Integration to link to** functionality provided by Qt Designer and its related libraries.**** Trolltech reserves all rights not expressly granted herein.**** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.******************************************************************************///#define QNATIVESOCKETENGINE_DEBUG/*! \class QNativeSocketEngine    \internal    \brief The QNativeSocketEngine class provides low level access to a socket.    \reentrant    \ingroup io    \module network    QtSocketLayer provides basic socket functionality provided by the    operating system. It also keeps track of what state the socket is    in, and which errors that occur.    The classes QTcpSocket, QUdpSocket and QTcpServer provide a    higher level API, and are in general more useful for the common    application.    There are two main ways of initializing the a QNativeSocketEngine; either    create a new socket by passing the socket type (TcpSocket or    UdpSocket) and network layer protocol (IPv4Protocol or    IPv6Protocol) to initialize(), or pass an existing socket    descriptor and have QNativeSocketEngine determine the type and protocol    itself. The native socket descriptor can later be fetched by    calling socketDescriptor(). The socket is made non-blocking, but    blocking behavior can still be achieved by calling waitForRead()    and waitForWrite(). isValid() can be called to check if the socket    has been successfully initialized and is ready to use.    To connect to a host, determine its address and pass this and the    port number to connectToHost(). The socket can then be used as a    TCP or UDP client. Otherwise; bind(), listen() and accept() are    used to have the socket function as a TCP or UDP server. Call    close() to close the socket.    bytesAvailable() is called to determine how much data is available    for reading. read() and write() are used by both TCP and UDP    clients to exchange data with the connected peer. UDP clients can    also call hasMoreDatagrams(), nextDatagramSize(),    readDatagram(), and writeDatagram().    Call state() to determine the state of the socket, for    example, ListeningState or ConnectedState. socketType() tells    whether the socket is a TCP socket or a UDP socket, or if the    socket type is unknown. protocol() is used to determine the    socket's network layer protocol.    localAddress(), localPort() are called to find the address and    port that are currently bound to the socket. If the socket is    connected, peerAddress() and peerPort() determine the address and    port of the connected peer.    Finally, if any function should fail, error() and    errorString() can be called to determine the cause of the error.*/#include "qnativesocketengine_p.h"#include <qabstracteventdispatcher.h>#include <qsocketnotifier.h>#include <private/qthread_p.h>//#define QNATIVESOCKETENGINE_DEBUG#define Q_VOID// Common constructs#define Q_CHECK_VALID_SOCKETLAYER(function, returnValue) do { \    if (!isValid()) { \        qWarning(""#function" was called on an uninitialized socket device"); \        return returnValue; \    } } while (0)#define Q_CHECK_INVALID_SOCKETLAYER(function, returnValue) do { \    if (isValid()) { \        qWarning(""#function" was called on an already initialized socket device"); \        return returnValue; \    } } while (0)#define Q_CHECK_STATE(function, checkState, returnValue) do { \    if (d->socketState != (checkState)) { \        qWarning(""#function" was not called in "#checkState); \        return (returnValue); \    } } while (0)#define Q_CHECK_NOT_STATE(function, checkState, returnValue) do { \    if (d->socketState == (checkState)) { \        qWarning(""#function" was called in "#checkState); \        return (returnValue); \    } } while (0)#define Q_CHECK_STATES(function, state1, state2, returnValue) do { \    if (d->socketState != (state1) && d->socketState != (state2)) { \        qWarning(""#function" was called" \                 " not in "#state1" or "#state2); \        return (returnValue); \    } } while (0)#define Q_CHECK_TYPE(function, type, returnValue) do { \    if (d->socketType != (type)) { \        qWarning(#function" was called by a" \                 " socket other than "#type""); \        return (returnValue); \    } } while (0)#define Q_TR(a) QT_TRANSLATE_NOOP(QNativeSocketEngine, a)/*! \internal    Constructs the private class and initializes all data members.    On Windows, WSAStartup is called "recursively" for every    concurrent QNativeSocketEngine. This is safe, because WSAStartup and    WSACleanup are reference counted.*/QNativeSocketEnginePrivate::QNativeSocketEnginePrivate(){    socketDescriptor = -1;    readNotifier = 0;    writeNotifier = 0;    exceptNotifier = 0;}/*! \internal    Destructs the private class.*/QNativeSocketEnginePrivate::~QNativeSocketEnginePrivate(){}/*! \internal    Sets the error and error string if not set already. The only    interesting error is the first one that occurred, and not the last    one.*/void QNativeSocketEnginePrivate::setError(QAbstractSocket::SocketError error, ErrorString errorString) const{    if (hasSetSocketError) {        // Only set socket errors once for one engine; expect the        // socket to recreate its engine after an error. Note: There's        // one exception: SocketError(11) bypasses this as it's purely        // a temporary internal error condition.        return;    }    if (error != QAbstractSocket::SocketError(11))        hasSetSocketError = true;    socketError = error;    switch (errorString) {    case NonBlockingInitFailedErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Unable to initialize non-blocking socket"));        break;    case BroadcastingInitFailedErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Unable to initialize broadcast socket"));        break;    case NoIpV6ErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Attempt to use IPv6 socket on a platform with no IPv6 support"));        break;    case RemoteHostClosedErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "The remote host closed the connection"));        break;    case TimeOutErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Network operation timed out"));        break;    case ResourceErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Out of resources"));        break;    case OperationUnsupportedErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Unsupported socket operation"));        break;    case ProtocolUnsupportedErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Protocol type not supported"));        break;    case InvalidSocketErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Invalid socket descriptor"));        break;    case HostUnreachableErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Host unreachable"));        break;    case NetworkUnreachableErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Network unreachable"));        break;    case AccessErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Permission denied"));        break;    case ConnectionTimeOutErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Connection timed out"));        break;    case ConnectionRefusedErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Connection refused"));        break;    case AddressInuseErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "The bound address is already in use"));        break;    case AddressNotAvailableErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "The address is not available"));        break;    case AddressProtectedErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "The address is protected"));        break;    case DatagramTooLargeErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Datagram was too large to send"));        break;    case SendDatagramErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Unable to send a message"));        break;    case ReceiveDatagramErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Unable to receive a message"));        break;    case WriteErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Unable to write"));        break;    case ReadErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Network error"));        break;    case PortInuseErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Another socket is already listening on the same port"));        break;    case NotSocketErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Operation on non-socket"));        break;    case UnknownSocketErrorString:        socketErrorString = QLatin1String(QT_TRANSLATE_NOOP("QNativeSocketEngine", "Unknown error"));        break;    }}/*!    Constructs a QNativeSocketEngine.    \sa initialize()*/QNativeSocketEngine::QNativeSocketEngine(QObject *parent)    : QAbstractSocketEngine(*new QNativeSocketEnginePrivate(), parent){}/*!    Destructs a QNativeSocketEngine.*/QNativeSocketEngine::~QNativeSocketEngine(){    close();}/*!    Initializes a QNativeSocketEngine by creating a new socket of type \a    socketType and network layer protocol \a protocol. Returns true on    success; otherwise returns false.    If the socket was already initialized, this function closes the    socket before reeinitializing it.    The new socket is non-blocking, and for UDP sockets it's also    broadcast enabled.*/bool QNativeSocketEngine::initialize(QAbstractSocket::SocketType socketType, QAbstractSocket::NetworkLayerProtocol protocol){    Q_D(QNativeSocketEngine);    if (isValid())        close();#if defined(QT_NO_IPV6)    if (protocol == QAbstractSocket::IPv6Protocol) {        d->setError(QAbstractSocket::UnsupportedSocketOperationError,                    QNativeSocketEnginePrivate::NoIpV6ErrorString);        return false;    }#endif    // Create the socket    if (!d->createNewSocket(socketType, protocol)) {#if defined (QNATIVESOCKETENGINE_DEBUG)        QString typeStr = QLatin1String("UnknownSocketType");        if (socketType == QAbstractSocket::TcpSocket) typeStr = QLatin1String("TcpSocket");        else if (socketType == QAbstractSocket::UdpSocket) typeStr = QLatin1String("UdpSocket");        QString protocolStr = QLatin1String("UnknownProtocol");        if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = QLatin1String("IPv4Protocol");        else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = QLatin1String("IPv6Protocol");        qDebug("QNativeSocketEngine::initialize(type == %s, protocol == %s) failed: %s",               typeStr.toLatin1().constData(), protocolStr.toLatin1().constData(), d->socketErrorString.toLatin1().constData());#endif        return false;    }    // Make the socket nonblocking.    if (!setOption(NonBlockingSocketOption, 1)) {        d->setError(QAbstractSocket::UnsupportedSocketOperationError,                    QNativeSocketEnginePrivate::NonBlockingInitFailedErrorString);        close();        return false;    }    // Set the broadcasting flag if it's a UDP socket.    if (socketType == QAbstractSocket::UdpSocket        && !setOption(BroadcastSocketOption, 1)) {        d->setError(QAbstractSocket::UnsupportedSocketOperationError,                    QNativeSocketEnginePrivate::BroadcastingInitFailedErrorString);        close();        return false;    }    // Make sure we receive out-of-band data    if (socketType == QAbstractSocket::TcpSocket        && !setOption(ReceiveOutOfBandData, 1)) {        qWarning("QNativeSocketEngine::initialize unable to inline out-of-band data");    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -