1 /****************************************************************************
3 ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtNetwork module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 //#define QABSTRACTSOCKET_DEBUG
45 \class QAbstractSocket
47 \brief The QAbstractSocket class provides the base functionality
48 common to all socket types.
54 QAbstractSocket is the base class for QTcpSocket and QUdpSocket
55 and contains all common functionality of these two classes. If
56 you need a socket, you have two options:
59 \i Instantiate QTcpSocket or QUdpSocket.
60 \i Create a native socket descriptor, instantiate
61 QAbstractSocket, and call setSocketDescriptor() to wrap the
65 TCP (Transmission Control Protocol) is a reliable,
66 stream-oriented, connection-oriented transport protocol. UDP
67 (User Datagram Protocol) is an unreliable, datagram-oriented,
68 connectionless protocol. In practice, this means that TCP is
69 better suited for continuous transmission of data, whereas the
70 more lightweight UDP can be used when reliability isn't
73 QAbstractSocket's API unifies most of the differences between the
74 two protocols. For example, although UDP is connectionless,
75 connectToHost() establishes a virtual connection for UDP sockets,
76 enabling you to use QAbstractSocket in more or less the same way
77 regardless of the underlying protocol. Internally,
78 QAbstractSocket remembers the address and port passed to
79 connectToHost(), and functions like read() and write() use these
82 At any time, QAbstractSocket has a state (returned by
83 state()). The initial state is UnconnectedState. After
84 calling connectToHost(), the socket first enters
85 HostLookupState. If the host is found, QAbstractSocket enters
86 ConnectingState and emits the hostFound() signal. When the
87 connection has been established, it enters ConnectedState and
88 emits connected(). If an error occurs at any stage, error() is
89 emitted. Whenever the state changes, stateChanged() is emitted.
90 For convenience, isValid() returns true if the socket is ready for
91 reading and writing, but note that the socket's state must be
92 ConnectedState before reading and writing can occur.
94 Read or write data by calling read() or write(), or use the
95 convenience functions readLine() and readAll(). QAbstractSocket
96 also inherits getChar(), putChar(), and ungetChar() from
97 QIODevice, which work on single bytes. The bytesWritten() signal
98 is emitted when data has been written to the socket (i.e., when
99 the client has read the data). Note that Qt does not limit the
100 write buffer size. You can monitor its size by listening to this
103 The readyRead() signal is emitted every time a new chunk of data
104 has arrived. bytesAvailable() then returns the number of bytes
105 that are available for reading. Typically, you would connect the
106 readyRead() signal to a slot and read all available data there.
107 If you don't read all the data at once, the remaining data will
108 still be available later, and any new incoming data will be
109 appended to QAbstractSocket's internal read buffer. To limit the
110 size of the read buffer, call setReadBufferSize().
112 To close the socket, call disconnectFromHost(). QAbstractSocket enters
113 QAbstractSocket::ClosingState. After all pending data has been written to
114 the socket, QAbstractSocket actually closes the socket, enters
115 QAbstractSocket::ClosedState, and emits disconnected(). If you want to
116 abort a connection immediately, discarding all pending data, call abort()
117 instead. If the remote host closes the connection, QAbstractSocket will
118 emit error(QAbstractSocket::RemoteHostClosedError), during which the socket
119 state will still be ConnectedState, and then the disconnected() signal
122 The port and address of the connected peer is fetched by calling
123 peerPort() and peerAddress(). peerName() returns the host name of
124 the peer, as passed to connectToHost(). localPort() and
125 localAddress() return the port and address of the local socket.
127 QAbstractSocket provides a set of functions that suspend the
128 calling thread until certain signals are emitted. These functions
129 can be used to implement blocking sockets:
132 \o waitForConnected() blocks until a connection has been established.
134 \o waitForReadyRead() blocks until new data is available for
137 \o waitForBytesWritten() blocks until one payload of data has been
138 written to the socket.
140 \o waitForDisconnected() blocks until the connection has closed.
145 \snippet doc/src/snippets/network/tcpwait.cpp 0
147 If \l{QIODevice::}{waitForReadyRead()} returns false, the
148 connection has been closed or an error has occurred.
150 Programming with a blocking socket is radically different from
151 programming with a non-blocking socket. A blocking socket doesn't
152 require an event loop and typically leads to simpler code.
153 However, in a GUI application, blocking sockets should only be
154 used in non-GUI threads, to avoid freezing the user interface.
155 See the \l network/fortuneclient and \l network/blockingfortuneclient
156 examples for an overview of both approaches.
158 \note We discourage the use of the blocking functions together
159 with signals. One of the two possibilities should be used.
161 QAbstractSocket can be used with QTextStream and QDataStream's
162 stream operators (operator<<() and operator>>()). There is one
163 issue to be aware of, though: You must make sure that enough data
164 is available before attempting to read it using operator>>().
166 \sa QFtp, QNetworkAccessManager, QTcpServer
170 \fn void QAbstractSocket::hostFound()
172 This signal is emitted after connectToHost() has been called and
173 the host lookup has succeeded.
175 \note Since Qt 4.6.3 QAbstractSocket may emit hostFound()
176 directly from the connectToHost() call since a DNS result could have been
183 \fn void QAbstractSocket::connected()
185 This signal is emitted after connectToHost() has been called and
186 a connection has been successfully established.
188 \note On some operating systems the connected() signal may
189 be directly emitted from the connectToHost() call for connections
192 \sa connectToHost(), disconnected()
196 \fn void QAbstractSocket::disconnected()
198 This signal is emitted when the socket has been disconnected.
200 \warning If you need to delete the sender() of this signal in a slot connected
201 to it, use the \l{QObject::deleteLater()}{deleteLater()} function.
203 \sa connectToHost(), disconnectFromHost(), abort()
207 \fn void QAbstractSocket::error(QAbstractSocket::SocketError socketError)
209 This signal is emitted after an error occurred. The \a socketError
210 parameter describes the type of error that occurred.
212 QAbstractSocket::SocketError is not a registered metatype, so for queued
213 connections, you will have to register it with Q_DECLARE_METATYPE() and
216 \sa error(), errorString(), {Creating Custom Qt Types}
220 \fn void QAbstractSocket::stateChanged(QAbstractSocket::SocketState socketState)
222 This signal is emitted whenever QAbstractSocket's state changes.
223 The \a socketState parameter is the new state.
225 QAbstractSocket::SocketState is not a registered metatype, so for queued
226 connections, you will have to register it with Q_REGISTER_METATYPE() and
229 \sa state(), {Creating Custom Qt Types}
233 \fn void QAbstractSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
236 This signal can be emitted when a \a proxy that requires
237 authentication is used. The \a authenticator object can then be
238 filled in with the required details to allow authentication and
239 continue the connection.
241 \note It is not possible to use a QueuedConnection to connect to
242 this signal, as the connection will fail if the authenticator has
243 not been filled in with new information when the signal returns.
245 \sa QAuthenticator, QNetworkProxy
249 \enum QAbstractSocket::NetworkLayerProtocol
251 This enum describes the network layer protocol values used in Qt.
253 \value IPv4Protocol IPv4
254 \value IPv6Protocol IPv6
255 \value UnknownNetworkLayerProtocol Other than IPv4 and IPv6
257 \sa QHostAddress::protocol()
261 \enum QAbstractSocket::SocketType
263 This enum describes the transport layer protocol.
267 \value UnknownSocketType Other than TCP and UDP
269 \sa QAbstractSocket::socketType()
273 \enum QAbstractSocket::SocketError
275 This enum describes the socket errors that can occur.
277 \value ConnectionRefusedError The connection was refused by the
279 \value RemoteHostClosedError The remote host closed the
280 connection. Note that the client socket (i.e., this socket)
281 will be closed after the remote close notification has
283 \value HostNotFoundError The host address was not found.
284 \value SocketAccessError The socket operation failed because the
285 application lacked the required privileges.
286 \value SocketResourceError The local system ran out of resources
287 (e.g., too many sockets).
288 \value SocketTimeoutError The socket operation timed out.
289 \value DatagramTooLargeError The datagram was larger than the
290 operating system's limit (which can be as low as 8192
292 \value NetworkError An error occurred with the network (e.g., the
293 network cable was accidentally plugged out).
294 \value AddressInUseError The address specified to QUdpSocket::bind() is
295 already in use and was set to be exclusive.
296 \value SocketAddressNotAvailableError The address specified to
297 QUdpSocket::bind() does not belong to the host.
298 \value UnsupportedSocketOperationError The requested socket operation is
299 not supported by the local operating system (e.g., lack of
301 \value ProxyAuthenticationRequiredError The socket is using a proxy, and
302 the proxy requires authentication.
303 \value SslHandshakeFailedError The SSL/TLS handshake failed, so
304 the connection was closed (only used in QSslSocket)
305 \value UnfinishedSocketOperationError Used by QAbstractSocketEngine only,
306 The last operation attempted has not finished yet (still in progress in
308 \value ProxyConnectionRefusedError Could not contact the proxy server because
309 the connection to that server was denied
310 \value ProxyConnectionClosedError The connection to the proxy server was closed
311 unexpectedly (before the connection to the final peer was established)
312 \value ProxyConnectionTimeoutError The connection to the proxy server timed out
313 or the proxy server stopped responding in the authentication phase.
314 \value ProxyNotFoundError The proxy address set with setProxy() (or the application
315 proxy) was not found.
316 \value ProxyProtocolError The connection negotiation with the proxy server
317 because the response from the proxy server could not be understood.
319 \value UnknownSocketError An unidentified error occurred.
320 \sa QAbstractSocket::error()
324 \enum QAbstractSocket::SocketState
326 This enum describes the different states in which a socket can be.
328 \value UnconnectedState The socket is not connected.
329 \value HostLookupState The socket is performing a host name lookup.
330 \value ConnectingState The socket has started establishing a connection.
331 \value ConnectedState A connection is established.
332 \value BoundState The socket is bound to an address and port (for servers).
333 \value ClosingState The socket is about to close (data may still
334 be waiting to be written).
335 \value ListeningState For internal use only.
337 \omitvalue HostLookup
338 \omitvalue Connecting
341 \omitvalue Connection
343 \sa QAbstractSocket::state()
347 \enum QAbstractSocket::SocketOption
350 This enum represents the options that can be set on a socket.
351 If desired, they can be set after having received the connected() signal from
352 the socket or after having received a new socket from a QTcpServer.
354 \value LowDelayOption Try to optimize the socket for low latency. For a QTcpSocket
355 this would set the TCP_NODELAY option and disable Nagle's algorithm. Set this to 1
357 \value KeepAliveOption Set this to 1 to enable the SO_KEEPALIVE socket option
359 \value MulticastTtlOption Set this to an integer value to set IP_MULTICAST_TTL (TTL for multicast datagrams) socket option.
361 \value MulticastLoopbackOption Set this to 1 to enable the IP_MULTICAST_LOOP (multicast loopback) socket option.
363 \sa QAbstractSocket::setSocketOption(), QAbstractSocket::socketOption()
366 #include "qabstractsocket.h"
367 #include "qabstractsocket_p.h"
369 #include "private/qhostinfo_p.h"
370 #include "private/qnetworksession_p.h"
372 #include <qabstracteventdispatcher.h>
373 #include <qhostaddress.h>
374 #include <qhostinfo.h>
375 #include <qmetaobject.h>
376 #include <qpointer.h>
378 #include <qelapsedtimer.h>
379 #include <qscopedvaluerollback.h>
381 #ifndef QT_NO_OPENSSL
382 #include <QtNetwork/qsslsocket.h>
385 #include <private/qthread_p.h>
387 #ifdef QABSTRACTSOCKET_DEBUG
393 #define Q_CHECK_SOCKETENGINE(returnValue) do { \
394 if (!d->socketEngine) { \
395 return returnValue; \
398 #ifndef QABSTRACTSOCKET_BUFFERSIZE
399 #define QABSTRACTSOCKET_BUFFERSIZE 32768
401 #define QT_CONNECT_TIMEOUT 30000
402 #define QT_TRANSFER_TIMEOUT 120000
406 #if defined QABSTRACTSOCKET_DEBUG
407 QT_BEGIN_INCLUDE_NAMESPACE
410 QT_END_INCLUDE_NAMESPACE
413 Returns a human readable representation of the first \a len
414 characters in \a data.
416 static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
418 if (!data) return "(null)";
420 for (int i = 0; i < len; ++i) {
422 if (isprint(int(uchar(c)))) {
425 case '\n': out += "\\n"; break;
426 case '\r': out += "\\r"; break;
427 case '\t': out += "\\t"; break;
430 tmp.sprintf("\\%o", c);
431 out += tmp.toLatin1();
442 static bool isProxyError(QAbstractSocket::SocketError error)
445 case QAbstractSocket::ProxyAuthenticationRequiredError:
446 case QAbstractSocket::ProxyConnectionRefusedError:
447 case QAbstractSocket::ProxyConnectionClosedError:
448 case QAbstractSocket::ProxyConnectionTimeoutError:
449 case QAbstractSocket::ProxyNotFoundError:
450 case QAbstractSocket::ProxyProtocolError:
459 Constructs a QAbstractSocketPrivate. Initializes all members.
461 QAbstractSocketPrivate::QAbstractSocketPrivate()
462 : readSocketNotifierCalled(false),
463 readSocketNotifierState(false),
464 readSocketNotifierStateSet(false),
465 emittedReadyRead(false),
466 emittedBytesWritten(false),
474 cachedSocketDescriptor(-1),
475 readBufferMaxSize(0),
476 readBuffer(QABSTRACTSOCKET_BUFFERSIZE),
477 writeBuffer(QABSTRACTSOCKET_BUFFERSIZE),
479 blockingTimeout(30000),
482 connectTimeElapsed(0),
484 socketType(QAbstractSocket::UnknownSocketType),
485 state(QAbstractSocket::UnconnectedState),
486 socketError(QAbstractSocket::UnknownSocketError)
492 Destructs the QAbstractSocket. If the socket layer is open, it
495 QAbstractSocketPrivate::~QAbstractSocketPrivate()
501 Resets the socket layer, clears the read and write buffers and
502 deletes any socket notifiers.
504 void QAbstractSocketPrivate::resetSocketLayer()
506 #if defined (QABSTRACTSOCKET_DEBUG)
507 qDebug("QAbstractSocketPrivate::resetSocketLayer()");
511 socketEngine->close();
512 socketEngine->disconnect();
515 cachedSocketDescriptor = -1;
518 connectTimer->stop();
520 disconnectTimer->stop();
525 Initializes the socket layer to by of type \a type, using the
526 network layer protocol \a protocol. Resets the socket layer first
527 if it's already initialized. Sets up the socket notifiers.
529 bool QAbstractSocketPrivate::initSocketLayer(QAbstractSocket::NetworkLayerProtocol protocol)
531 #ifdef QT_NO_NETWORKPROXY
532 // this is here to avoid a duplication of the call to createSocketEngine below
533 static const QNetworkProxy &proxyInUse = *(QNetworkProxy *)0;
536 Q_Q(QAbstractSocket);
537 #if defined (QABSTRACTSOCKET_DEBUG)
539 if (q->socketType() == QAbstractSocket::TcpSocket) typeStr = QLatin1String("TcpSocket");
540 else if (q->socketType() == QAbstractSocket::UdpSocket) typeStr = QLatin1String("UdpSocket");
541 else typeStr = QLatin1String("UnknownSocketType");
543 if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = QLatin1String("IPv4Protocol");
544 else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = QLatin1String("IPv6Protocol");
545 else protocolStr = QLatin1String("UnknownNetworkLayerProtocol");
549 socketEngine = QAbstractSocketEngine::createSocketEngine(q->socketType(), proxyInUse, q);
551 socketError = QAbstractSocket::UnsupportedSocketOperationError;
552 q->setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
555 #ifndef QT_NO_BEARERMANAGEMENT
556 //copy network session down to the socket engine (if it has been set)
557 socketEngine->setProperty("_q_networksession", q->property("_q_networksession"));
559 #ifndef QT_NO_NETWORKPROXY
560 //copy user agent to socket engine (if it has been set)
561 socketEngine->setProperty("_q_user-agent", q->property("_q_user-agent"));
563 if (!socketEngine->initialize(q->socketType(), protocol)) {
564 #if defined (QABSTRACTSOCKET_DEBUG)
565 qDebug("QAbstractSocketPrivate::initSocketLayer(%s, %s) failed (%s)",
566 typeStr.toLatin1().constData(), protocolStr.toLatin1().constData(),
567 socketEngine->errorString().toLatin1().constData());
569 socketError = socketEngine->error();
570 q->setErrorString(socketEngine->errorString());
574 if (threadData->eventDispatcher)
575 socketEngine->setReceiver(this);
577 #if defined (QABSTRACTSOCKET_DEBUG)
578 qDebug("QAbstractSocketPrivate::initSocketLayer(%s, %s) success",
579 typeStr.toLatin1().constData(), protocolStr.toLatin1().constData());
586 Slot connected to the read socket notifier. This slot is called
587 when new data is available for reading, or when the socket has
588 been closed. Handles recursive calls.
590 bool QAbstractSocketPrivate::canReadNotification()
592 Q_Q(QAbstractSocket);
593 #if defined (QABSTRACTSOCKET_DEBUG)
594 qDebug("QAbstractSocketPrivate::canReadNotification()");
597 // Prevent recursive calls
598 if (readSocketNotifierCalled) {
599 if (!readSocketNotifierStateSet) {
600 readSocketNotifierStateSet = true;
601 readSocketNotifierState = socketEngine->isReadNotificationEnabled();
602 socketEngine->setReadNotificationEnabled(false);
605 QScopedValueRollback<bool> rsncrollback(readSocketNotifierCalled);
606 readSocketNotifierCalled = true;
609 socketEngine->setReadNotificationEnabled(false);
611 // If buffered, read data from the socket into the read buffer
614 // Return if there is no space in the buffer
615 if (readBufferMaxSize && readBuffer.size() >= readBufferMaxSize) {
616 #if defined (QABSTRACTSOCKET_DEBUG)
617 qDebug("QAbstractSocketPrivate::canReadNotification() buffer is full");
622 // If reading from the socket fails after getting a read
623 // notification, close the socket.
624 newBytes = readBuffer.size();
625 if (!readFromSocket()) {
626 #if defined (QABSTRACTSOCKET_DEBUG)
627 qDebug("QAbstractSocketPrivate::canReadNotification() disconnecting socket");
629 q->disconnectFromHost();
632 newBytes = readBuffer.size() - newBytes;
634 // If read buffer is full, disable the read socket notifier.
635 if (readBufferMaxSize && readBuffer.size() == readBufferMaxSize) {
636 socketEngine->setReadNotificationEnabled(false);
640 // only emit readyRead() when not recursing, and only if there is data available
641 bool hasData = newBytes > 0
642 #ifndef QT_NO_UDPSOCKET
643 || (!isBuffered && socketType != QAbstractSocket::TcpSocket && socketEngine && socketEngine->hasPendingDatagrams())
645 || (!isBuffered && socketType == QAbstractSocket::TcpSocket && socketEngine)
648 if (!emittedReadyRead && hasData) {
649 QScopedValueRollback<bool> r(emittedReadyRead);
650 emittedReadyRead = true;
654 // If we were closed as a result of the readyRead() signal,
656 if (state == QAbstractSocket::UnconnectedState || state == QAbstractSocket::ClosingState) {
657 #if defined (QABSTRACTSOCKET_DEBUG)
658 qDebug("QAbstractSocketPrivate::canReadNotification() socket is closing - returning");
663 if (!hasData && socketEngine)
664 socketEngine->setReadNotificationEnabled(true);
666 // reset the read socket notifier state if we reentered inside the
667 // readyRead() connected slot.
668 if (readSocketNotifierStateSet && socketEngine &&
669 readSocketNotifierState != socketEngine->isReadNotificationEnabled()) {
670 socketEngine->setReadNotificationEnabled(readSocketNotifierState);
671 readSocketNotifierStateSet = false;
678 Slot connected to the write socket notifier. It's called during a
679 delayed connect or when the socket is ready for writing.
681 bool QAbstractSocketPrivate::canWriteNotification()
683 #if defined (Q_OS_WIN)
684 if (socketEngine && socketEngine->isWriteNotificationEnabled())
685 socketEngine->setWriteNotificationEnabled(false);
688 #if defined (QABSTRACTSOCKET_DEBUG)
689 qDebug("QAbstractSocketPrivate::canWriteNotification() flushing");
691 int tmp = writeBuffer.size();
695 #if defined (Q_OS_WIN)
696 if (!writeBuffer.isEmpty())
697 socketEngine->setWriteNotificationEnabled(true);
699 if (writeBuffer.isEmpty() && socketEngine->bytesToWrite() == 0)
700 socketEngine->setWriteNotificationEnabled(false);
704 return (writeBuffer.size() < tmp);
709 Slot connected to a notification of connection status
710 change. Either we finished connecting or we failed to connect.
712 void QAbstractSocketPrivate::connectionNotification()
714 // If in connecting state, check if the connection has been
715 // established, otherwise flush pending data.
716 if (state == QAbstractSocket::ConnectingState) {
717 #if defined (QABSTRACTSOCKET_DEBUG)
718 qDebug("QAbstractSocketPrivate::connectionNotification() testing connection");
726 Writes pending data in the write buffers to the socket. The
727 function writes as much as it can without blocking.
729 It is usually invoked by canWriteNotification after one or more
732 Emits bytesWritten().
734 bool QAbstractSocketPrivate::flush()
736 Q_Q(QAbstractSocket);
737 if (!socketEngine || !socketEngine->isValid() || (writeBuffer.isEmpty()
738 && socketEngine->bytesToWrite() == 0)) {
739 #if defined (QABSTRACTSOCKET_DEBUG)
740 qDebug("QAbstractSocketPrivate::flush() nothing to do: valid ? %s, writeBuffer.isEmpty() ? %s",
741 socketEngine->isValid() ? "yes" : "no", writeBuffer.isEmpty() ? "yes" : "no");
744 // this covers the case when the buffer was empty, but we had to wait for the socket engine to finish
745 if (state == QAbstractSocket::ClosingState)
746 q->disconnectFromHost();
751 int nextSize = writeBuffer.nextDataBlockSize();
752 const char *ptr = writeBuffer.readPointer();
754 // Attempt to write it all in one chunk.
755 qint64 written = socketEngine->write(ptr, nextSize);
757 socketError = socketEngine->error();
758 q->setErrorString(socketEngine->errorString());
759 #if defined (QABSTRACTSOCKET_DEBUG)
760 qDebug() << "QAbstractSocketPrivate::flush() write error, aborting." << socketEngine->errorString();
762 emit q->error(socketError);
763 // an unexpected error so close the socket.
768 #if defined (QABSTRACTSOCKET_DEBUG)
769 qDebug("QAbstractSocketPrivate::flush() %lld bytes written to the network",
773 // Remove what we wrote so far.
774 writeBuffer.free(written);
776 // Don't emit bytesWritten() recursively.
777 if (!emittedBytesWritten) {
778 QScopedValueRollback<bool> r(emittedBytesWritten);
779 emittedBytesWritten = true;
780 emit q->bytesWritten(written);
784 if (writeBuffer.isEmpty() && socketEngine && socketEngine->isWriteNotificationEnabled()
785 && !socketEngine->bytesToWrite())
786 socketEngine->setWriteNotificationEnabled(false);
787 if (state == QAbstractSocket::ClosingState)
788 q->disconnectFromHost();
793 #ifndef QT_NO_NETWORKPROXY
796 Resolve the proxy to its final value.
798 void QAbstractSocketPrivate::resolveProxy(const QString &hostname, quint16 port)
801 if (hostname == QLatin1String("localhost")
802 || hostname.startsWith(QLatin1String("localhost."))
803 || (parsed.setAddress(hostname)
804 && (parsed == QHostAddress::LocalHost
805 || parsed == QHostAddress::LocalHostIPv6))) {
806 proxyInUse = QNetworkProxy::NoProxy;
810 QList<QNetworkProxy> proxies;
812 if (proxy.type() != QNetworkProxy::DefaultProxy) {
813 // a non-default proxy was set with setProxy
816 // try the application settings instead
817 QNetworkProxyQuery query(hostname, port, QString(),
818 socketType == QAbstractSocket::TcpSocket ?
819 QNetworkProxyQuery::TcpSocket :
820 QNetworkProxyQuery::UdpSocket);
821 proxies = QNetworkProxyFactory::proxyForQuery(query);
824 // return the first that we can use
825 foreach (const QNetworkProxy &p, proxies) {
826 if (socketType == QAbstractSocket::UdpSocket &&
827 (p.capabilities() & QNetworkProxy::UdpTunnelingCapability) == 0)
830 if (socketType == QAbstractSocket::TcpSocket &&
831 (p.capabilities() & QNetworkProxy::TunnelingCapability) == 0)
839 // DefaultProxy here will raise an error
840 proxyInUse = QNetworkProxy();
846 Starts the connection to \a host, like _q_startConnecting below,
847 but without hostname resolution.
849 void QAbstractSocketPrivate::startConnectingByName(const QString &host)
851 Q_Q(QAbstractSocket);
852 if (state == QAbstractSocket::ConnectingState || state == QAbstractSocket::ConnectedState)
855 #if defined(QABSTRACTSOCKET_DEBUG)
856 qDebug("QAbstractSocketPrivate::startConnectingByName(host == %s)", qPrintable(host));
859 // ### Let the socket engine drive this?
860 state = QAbstractSocket::ConnectingState;
861 emit q->stateChanged(state);
863 connectTimeElapsed = 0;
865 if (initSocketLayer(QAbstractSocket::UnknownNetworkLayerProtocol)) {
866 if (socketEngine->connectToHostByName(host, port) ||
867 socketEngine->state() == QAbstractSocket::ConnectingState) {
868 cachedSocketDescriptor = socketEngine->socketDescriptor();
874 socketError = socketEngine->error();
875 q->setErrorString(socketEngine->errorString());
878 state = QAbstractSocket::UnconnectedState;
879 emit q->error(socketError);
880 emit q->stateChanged(state);
887 Slot connected to QHostInfo::lookupHost() in connectToHost(). This
888 function starts the process of connecting to any number of
889 candidate IP addresses for the host, if it was found. Calls
890 _q_connectToNextAddress().
892 void QAbstractSocketPrivate::_q_startConnecting(const QHostInfo &hostInfo)
894 Q_Q(QAbstractSocket);
895 if (state != QAbstractSocket::HostLookupState)
898 if (hostLookupId != -1 && hostLookupId != hostInfo.lookupId()) {
899 qWarning("QAbstractSocketPrivate::_q_startConnecting() received hostInfo for wrong lookup ID %d expected %d", hostInfo.lookupId(), hostLookupId);
902 addresses = hostInfo.addresses();
904 #if defined(QABSTRACTSOCKET_DEBUG)
905 QString s = QLatin1String("{");
906 for (int i = 0; i < addresses.count(); ++i) {
907 if (i != 0) s += QLatin1String(", ");
908 s += addresses.at(i).toString();
910 s += QLatin1Char('}');
911 qDebug("QAbstractSocketPrivate::_q_startConnecting(hostInfo == %s)", s.toLatin1().constData());
914 // Try all addresses twice.
915 addresses += addresses;
917 // If there are no addresses in the host list, report this to the
919 if (addresses.isEmpty()) {
920 #if defined(QABSTRACTSOCKET_DEBUG)
921 qDebug("QAbstractSocketPrivate::_q_startConnecting(), host not found");
923 state = QAbstractSocket::UnconnectedState;
924 socketError = QAbstractSocket::HostNotFoundError;
925 q->setErrorString(QAbstractSocket::tr("Host not found"));
926 emit q->stateChanged(state);
927 emit q->error(QAbstractSocket::HostNotFoundError);
931 // Enter Connecting state (see also sn_write, which is called by
932 // the write socket notifier after connect())
933 state = QAbstractSocket::ConnectingState;
934 emit q->stateChanged(state);
936 // Report the successful host lookup
939 // Reset the total time spent connecting.
940 connectTimeElapsed = 0;
942 // The addresses returned by the lookup will be tested one after
943 // another by _q_connectToNextAddress().
944 _q_connectToNextAddress();
949 Called by a queued or direct connection from _q_startConnecting() or
950 _q_testConnection(), this function takes the first address of the
951 pending addresses list and tries to connect to it. If the
952 connection succeeds, QAbstractSocket will emit
953 connected(). Otherwise, error(ConnectionRefusedError) or
954 error(SocketTimeoutError) is emitted.
956 void QAbstractSocketPrivate::_q_connectToNextAddress()
958 Q_Q(QAbstractSocket);
960 // Check for more pending addresses
961 if (addresses.isEmpty()) {
962 #if defined(QABSTRACTSOCKET_DEBUG)
963 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), all addresses failed.");
965 state = QAbstractSocket::UnconnectedState;
967 if ((socketEngine->error() == QAbstractSocket::UnknownSocketError
969 // On AIX, the second connect call will result in EINVAL and not
970 // ECONNECTIONREFUSED; although the meaning is the same.
971 || socketEngine->error() == QAbstractSocket::UnsupportedSocketOperationError
973 ) && socketEngine->state() == QAbstractSocket::ConnectingState) {
974 socketError = QAbstractSocket::ConnectionRefusedError;
975 q->setErrorString(QAbstractSocket::tr("Connection refused"));
977 socketError = socketEngine->error();
978 q->setErrorString(socketEngine->errorString());
981 // socketError = QAbstractSocket::ConnectionRefusedError;
982 // q->setErrorString(QAbstractSocket::tr("Connection refused"));
984 emit q->stateChanged(state);
985 emit q->error(socketError);
989 // Pick the first host address candidate
990 host = addresses.takeFirst();
991 #if defined(QABSTRACTSOCKET_DEBUG)
992 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), connecting to %s:%i, %d left to try",
993 host.toString().toLatin1().constData(), port, addresses.count());
996 #if defined(QT_NO_IPV6)
997 if (host.protocol() == QAbstractSocket::IPv6Protocol) {
998 // If we have no IPv6 support, then we will not be able to
999 // connect. So we just pretend we didn't see this address.
1000 #if defined(QABSTRACTSOCKET_DEBUG)
1001 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), skipping IPv6 entry");
1007 if (!initSocketLayer(host.protocol())) {
1008 // hope that the next address is better
1009 #if defined(QABSTRACTSOCKET_DEBUG)
1010 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), failed to initialize sock layer");
1015 // Tries to connect to the address. If it succeeds immediately
1016 // (localhost address on BSD or any UDP connect), emit
1017 // connected() and return.
1018 if (socketEngine->connectToHost(host, port)) {
1019 //_q_testConnection();
1020 fetchConnectionParameters();
1024 // cache the socket descriptor even if we're not fully connected yet
1025 cachedSocketDescriptor = socketEngine->socketDescriptor();
1027 // Check that we're in delayed connection state. If not, try
1029 if (socketEngine->state() != QAbstractSocket::ConnectingState) {
1030 #if defined(QABSTRACTSOCKET_DEBUG)
1031 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), connection failed (%s)",
1032 socketEngine->errorString().toLatin1().constData());
1037 // Start the connect timer.
1038 if (threadData->eventDispatcher) {
1039 if (!connectTimer) {
1040 connectTimer = new QTimer(q);
1041 QObject::connect(connectTimer, SIGNAL(timeout()),
1042 q, SLOT(_q_abortConnectionAttempt()),
1043 Qt::DirectConnection);
1045 connectTimer->start(QT_CONNECT_TIMEOUT);
1048 // Wait for a write notification that will eventually call
1049 // _q_testConnection().
1050 socketEngine->setWriteNotificationEnabled(true);
1052 } while (state != QAbstractSocket::ConnectedState);
1057 Tests if a connection has been established. If it has, connected()
1058 is emitted. Otherwise, _q_connectToNextAddress() is invoked.
1060 void QAbstractSocketPrivate::_q_testConnection()
1063 if (threadData->eventDispatcher) {
1065 connectTimer->stop();
1068 if (socketEngine->state() == QAbstractSocket::ConnectedState) {
1069 // Fetch the parameters if our connection is completed;
1070 // otherwise, fall out and try the next address.
1071 fetchConnectionParameters();
1073 q_func()->disconnectFromHost();
1074 pendingClose = false;
1079 // don't retry the other addresses if we had a proxy error
1080 if (isProxyError(socketEngine->error()))
1084 if (threadData->eventDispatcher) {
1086 connectTimer->stop();
1089 #if defined(QABSTRACTSOCKET_DEBUG)
1090 qDebug("QAbstractSocketPrivate::_q_testConnection() connection failed,"
1091 " checking for alternative addresses");
1093 _q_connectToNextAddress();
1098 This function is called after a certain number of seconds has
1099 passed while waiting for a connection. It simply tests the
1100 connection, and continues to the next address if the connection
1103 void QAbstractSocketPrivate::_q_abortConnectionAttempt()
1105 Q_Q(QAbstractSocket);
1106 #if defined(QABSTRACTSOCKET_DEBUG)
1107 qDebug("QAbstractSocketPrivate::_q_abortConnectionAttempt() (timed out)");
1110 socketEngine->setWriteNotificationEnabled(false);
1112 connectTimer->stop();
1114 if (addresses.isEmpty()) {
1115 state = QAbstractSocket::UnconnectedState;
1116 socketError = QAbstractSocket::SocketTimeoutError;
1117 q->setErrorString(QAbstractSocket::tr("Connection timed out"));
1118 emit q->stateChanged(state);
1119 emit q->error(socketError);
1121 _q_connectToNextAddress();
1125 void QAbstractSocketPrivate::_q_forceDisconnect()
1127 Q_Q(QAbstractSocket);
1128 if (socketEngine && socketEngine->isValid() && state == QAbstractSocket::ClosingState) {
1129 socketEngine->close();
1130 q->disconnectFromHost();
1136 Reads data from the socket layer into the read buffer. Returns
1137 true on success; otherwise false.
1139 bool QAbstractSocketPrivate::readFromSocket()
1141 Q_Q(QAbstractSocket);
1142 // Find how many bytes we can read from the socket layer.
1143 qint64 bytesToRead = socketEngine->bytesAvailable();
1144 if (bytesToRead == 0) {
1145 // Under heavy load, certain conditions can trigger read notifications
1146 // for socket notifiers on which there is no activity. If we continue
1147 // to read 0 bytes from the socket, we will trigger behavior similar
1148 // to that which signals a remote close. When we hit this condition,
1149 // we try to read 4k of data from the socket, which will give us either
1150 // an EAGAIN/EWOULDBLOCK if the connection is alive (i.e., the remote
1151 // host has _not_ disappeared).
1154 if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - readBuffer.size()))
1155 bytesToRead = readBufferMaxSize - readBuffer.size();
1157 #if defined(QABSTRACTSOCKET_DEBUG)
1158 qDebug("QAbstractSocketPrivate::readFromSocket() about to read %d bytes",
1162 // Read from the socket, store data in the read buffer.
1163 char *ptr = readBuffer.reserve(bytesToRead);
1164 qint64 readBytes = socketEngine->read(ptr, bytesToRead);
1165 if (readBytes == -2) {
1166 // No bytes currently available for reading.
1167 readBuffer.chop(bytesToRead);
1170 readBuffer.chop(int(bytesToRead - (readBytes < 0 ? qint64(0) : readBytes)));
1171 #if defined(QABSTRACTSOCKET_DEBUG)
1172 qDebug("QAbstractSocketPrivate::readFromSocket() got %d bytes, buffer size = %d",
1173 int(readBytes), readBuffer.size());
1176 if (!socketEngine->isValid()) {
1177 socketError = socketEngine->error();
1178 q->setErrorString(socketEngine->errorString());
1179 emit q->error(socketError);
1180 #if defined(QABSTRACTSOCKET_DEBUG)
1181 qDebug("QAbstractSocketPrivate::readFromSocket() read failed: %s",
1182 q->errorString().toLatin1().constData());
1193 Sets up the internal state after the connection has succeeded.
1195 void QAbstractSocketPrivate::fetchConnectionParameters()
1197 Q_Q(QAbstractSocket);
1199 peerName = hostName;
1201 socketEngine->setReadNotificationEnabled(true);
1202 socketEngine->setWriteNotificationEnabled(true);
1203 localPort = socketEngine->localPort();
1204 peerPort = socketEngine->peerPort();
1205 localAddress = socketEngine->localAddress();
1206 peerAddress = socketEngine->peerAddress();
1207 cachedSocketDescriptor = socketEngine->socketDescriptor();
1210 state = QAbstractSocket::ConnectedState;
1211 emit q->stateChanged(state);
1212 emit q->connected();
1214 #if defined(QABSTRACTSOCKET_DEBUG)
1215 qDebug("QAbstractSocketPrivate::fetchConnectionParameters() connection to %s:%i established",
1216 host.toString().toLatin1().constData(), port);
1221 void QAbstractSocketPrivate::pauseSocketNotifiers(QAbstractSocket *socket)
1223 QAbstractSocketEngine *socketEngine = socket->d_func()->socketEngine;
1226 socket->d_func()->prePauseReadSocketNotifierState = socketEngine->isReadNotificationEnabled();
1227 socket->d_func()->prePauseWriteSocketNotifierState = socketEngine->isWriteNotificationEnabled();
1228 socket->d_func()->prePauseExceptionSocketNotifierState = socketEngine->isExceptionNotificationEnabled();
1229 socketEngine->setReadNotificationEnabled(false);
1230 socketEngine->setWriteNotificationEnabled(false);
1231 socketEngine->setExceptionNotificationEnabled(false);
1234 void QAbstractSocketPrivate::resumeSocketNotifiers(QAbstractSocket *socket)
1236 QAbstractSocketEngine *socketEngine = socket->d_func()->socketEngine;
1239 socketEngine->setReadNotificationEnabled(socket->d_func()->prePauseReadSocketNotifierState);
1240 socketEngine->setWriteNotificationEnabled(socket->d_func()->prePauseWriteSocketNotifierState);
1241 socketEngine->setExceptionNotificationEnabled(socket->d_func()->prePauseExceptionSocketNotifierState);
1244 QAbstractSocketEngine* QAbstractSocketPrivate::getSocketEngine(QAbstractSocket *socket)
1246 return socket->d_func()->socketEngine;
1252 Constructs a new abstract socket of type \a socketType. The \a
1253 parent argument is passed to QObject's constructor.
1255 QAbstractSocket::QAbstractSocket(SocketType socketType,
1256 QAbstractSocketPrivate &dd, QObject *parent)
1257 : QIODevice(dd, parent)
1259 Q_D(QAbstractSocket);
1260 #if defined(QABSTRACTSOCKET_DEBUG)
1261 qDebug("QAbstractSocket::QAbstractSocket(%sSocket, QAbstractSocketPrivate == %p, parent == %p)",
1262 socketType == TcpSocket ? "Tcp" : socketType == UdpSocket
1263 ? "Udp" : "Unknown", &dd, parent);
1265 d->socketType = socketType;
1269 Creates a new abstract socket of type \a socketType. The \a
1270 parent argument is passed to QObject's constructor.
1272 \sa socketType(), QTcpSocket, QUdpSocket
1274 QAbstractSocket::QAbstractSocket(SocketType socketType, QObject *parent)
1275 : QIODevice(*new QAbstractSocketPrivate, parent)
1277 Q_D(QAbstractSocket);
1278 #if defined(QABSTRACTSOCKET_DEBUG)
1279 qDebug("QAbstractSocket::QAbstractSocket(%p)", parent);
1281 d->socketType = socketType;
1285 Destroys the socket.
1287 QAbstractSocket::~QAbstractSocket()
1289 Q_D(QAbstractSocket);
1290 #if defined(QABSTRACTSOCKET_DEBUG)
1291 qDebug("QAbstractSocket::~QAbstractSocket()");
1293 if (d->state != UnconnectedState)
1298 Returns true if the socket is valid and ready for use; otherwise
1301 \bold{Note:} The socket's state must be ConnectedState before reading and
1306 bool QAbstractSocket::isValid() const
1308 return d_func()->socketEngine ? d_func()->socketEngine->isValid() : isOpen();
1312 Attempts to make a connection to \a hostName on the given \a port.
1314 The socket is opened in the given \a openMode and first enters
1315 HostLookupState, then performs a host name lookup of \a hostName.
1316 If the lookup succeeds, hostFound() is emitted and QAbstractSocket
1317 enters ConnectingState. It then attempts to connect to the address
1318 or addresses returned by the lookup. Finally, if a connection is
1319 established, QAbstractSocket enters ConnectedState and
1322 At any point, the socket can emit error() to signal that an error
1325 \a hostName may be an IP address in string form (e.g.,
1326 "43.195.83.32"), or it may be a host name (e.g.,
1327 "example.com"). QAbstractSocket will do a lookup only if
1328 required. \a port is in native byte order.
1330 \sa state(), peerName(), peerAddress(), peerPort(), waitForConnected()
1332 void QAbstractSocket::connectToHost(const QString &hostName, quint16 port,
1335 QMetaObject::invokeMethod(this, "connectToHostImplementation",
1336 Qt::DirectConnection,
1337 Q_ARG(QString, hostName),
1338 Q_ARG(quint16, port),
1339 Q_ARG(OpenMode, openMode));
1345 Contains the implementation of connectToHost().
1347 Attempts to make a connection to \a hostName on the given \a
1348 port. The socket is opened in the given \a openMode.
1350 void QAbstractSocket::connectToHostImplementation(const QString &hostName, quint16 port,
1353 Q_D(QAbstractSocket);
1354 #if defined(QABSTRACTSOCKET_DEBUG)
1355 qDebug("QAbstractSocket::connectToHost(\"%s\", %i, %i)...", qPrintable(hostName), port,
1359 if (d->state == ConnectedState || d->state == ConnectingState
1360 || d->state == ClosingState || d->state == HostLookupState) {
1361 qWarning("QAbstractSocket::connectToHost() called when already looking up or connecting/connected to \"%s\"", qPrintable(hostName));
1365 d->hostName = hostName;
1367 d->state = UnconnectedState;
1368 d->readBuffer.clear();
1369 d->writeBuffer.clear();
1370 d->abortCalled = false;
1371 d->closeCalled = false;
1372 d->pendingClose = false;
1375 d->localAddress.clear();
1376 d->peerAddress.clear();
1377 d->peerName = hostName;
1378 if (d->hostLookupId != -1) {
1379 QHostInfo::abortHostLookup(d->hostLookupId);
1380 d->hostLookupId = -1;
1383 #ifndef QT_NO_NETWORKPROXY
1384 // Get the proxy information
1385 d->resolveProxy(hostName, port);
1386 if (d->proxyInUse.type() == QNetworkProxy::DefaultProxy) {
1387 // failed to setup the proxy
1388 d->socketError = QAbstractSocket::UnsupportedSocketOperationError;
1389 setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
1390 emit error(d->socketError);
1395 if (openMode & QIODevice::Unbuffered)
1396 d->isBuffered = false; // Unbuffered QTcpSocket
1397 else if (!d_func()->isBuffered)
1398 openMode |= QAbstractSocket::Unbuffered; // QUdpSocket
1400 QIODevice::open(openMode);
1401 d->state = HostLookupState;
1402 emit stateChanged(d->state);
1405 if (temp.setAddress(hostName)) {
1407 info.setAddresses(QList<QHostAddress>() << temp);
1408 d->_q_startConnecting(info);
1409 #ifndef QT_NO_NETWORKPROXY
1410 } else if (d->proxyInUse.capabilities() & QNetworkProxy::HostNameLookupCapability) {
1411 // the proxy supports connection by name, so use it
1412 d->startConnectingByName(hostName);
1416 if (d->threadData->eventDispatcher) {
1417 // this internal API for QHostInfo either immediately gives us the desired
1418 // QHostInfo from cache or later calls the _q_startConnecting slot.
1419 bool immediateResultValid = false;
1420 QHostInfo hostInfo = qt_qhostinfo_lookup(hostName,
1422 SLOT(_q_startConnecting(QHostInfo)),
1423 &immediateResultValid,
1425 if (immediateResultValid) {
1426 d->hostLookupId = -1;
1427 d->_q_startConnecting(hostInfo);
1432 #if defined(QABSTRACTSOCKET_DEBUG)
1433 qDebug("QAbstractSocket::connectToHost(\"%s\", %i) == %s%s", hostName.toLatin1().constData(), port,
1434 (d->state == ConnectedState) ? "true" : "false",
1435 (d->state == ConnectingState || d->state == HostLookupState)
1436 ? " (connection in progress)" : "");
1442 Attempts to make a connection to \a address on port \a port.
1444 void QAbstractSocket::connectToHost(const QHostAddress &address, quint16 port,
1447 #if defined(QABSTRACTSOCKET_DEBUG)
1448 qDebug("QAbstractSocket::connectToHost([%s], %i, %i)...",
1449 address.toString().toLatin1().constData(), port, (int) openMode);
1451 connectToHost(address.toString(), port, openMode);
1455 Returns the number of bytes that are waiting to be written. The
1456 bytes are written when control goes back to the event loop or
1457 when flush() is called.
1459 \sa bytesAvailable(), flush()
1461 qint64 QAbstractSocket::bytesToWrite() const
1463 Q_D(const QAbstractSocket);
1464 #if defined(QABSTRACTSOCKET_DEBUG)
1465 qDebug("QAbstractSocket::bytesToWrite() == %i", d->writeBuffer.size());
1467 return (qint64)d->writeBuffer.size();
1471 Returns the number of incoming bytes that are waiting to be read.
1473 \sa bytesToWrite(), read()
1475 qint64 QAbstractSocket::bytesAvailable() const
1477 Q_D(const QAbstractSocket);
1478 qint64 available = QIODevice::bytesAvailable();
1480 available += (qint64) d->readBuffer.size();
1482 if (!d->isBuffered && d->socketEngine && d->socketEngine->isValid())
1483 available += d->socketEngine->bytesAvailable();
1485 #if defined(QABSTRACTSOCKET_DEBUG)
1486 qDebug("QAbstractSocket::bytesAvailable() == %llu", available);
1492 Returns the host port number (in native byte order) of the local
1493 socket if available; otherwise returns 0.
1495 \sa localAddress(), peerPort(), setLocalPort()
1497 quint16 QAbstractSocket::localPort() const
1499 Q_D(const QAbstractSocket);
1500 return d->localPort;
1504 Returns the host address of the local socket if available;
1505 otherwise returns QHostAddress::Null.
1507 This is normally the main IP address of the host, but can be
1508 QHostAddress::LocalHost (127.0.0.1) for connections to the
1511 \sa localPort(), peerAddress(), setLocalAddress()
1513 QHostAddress QAbstractSocket::localAddress() const
1515 Q_D(const QAbstractSocket);
1516 return d->localAddress;
1520 Returns the port of the connected peer if the socket is in
1521 ConnectedState; otherwise returns 0.
1523 \sa peerAddress(), localPort(), setPeerPort()
1525 quint16 QAbstractSocket::peerPort() const
1527 Q_D(const QAbstractSocket);
1532 Returns the address of the connected peer if the socket is in
1533 ConnectedState; otherwise returns QHostAddress::Null.
1535 \sa peerName(), peerPort(), localAddress(), setPeerAddress()
1537 QHostAddress QAbstractSocket::peerAddress() const
1539 Q_D(const QAbstractSocket);
1540 return d->peerAddress;
1544 Returns the name of the peer as specified by connectToHost(), or
1545 an empty QString if connectToHost() has not been called.
1547 \sa peerAddress(), peerPort(), setPeerName()
1549 QString QAbstractSocket::peerName() const
1551 Q_D(const QAbstractSocket);
1552 return d->peerName.isEmpty() ? d->hostName : d->peerName;
1556 Returns true if a line of data can be read from the socket;
1557 otherwise returns false.
1561 bool QAbstractSocket::canReadLine() const
1563 bool hasLine = d_func()->readBuffer.canReadLine();
1564 #if defined (QABSTRACTSOCKET_DEBUG)
1565 qDebug("QAbstractSocket::canReadLine() == %s, buffer size = %d, size = %d", hasLine ? "true" : "false",
1566 d_func()->readBuffer.size(), d_func()->buffer.size());
1568 return hasLine || QIODevice::canReadLine();
1572 Returns the native socket descriptor of the QAbstractSocket object
1573 if this is available; otherwise returns -1.
1575 If the socket is using QNetworkProxy, the returned descriptor
1576 may not be usable with native socket functions.
1578 The socket descriptor is not available when QAbstractSocket is in
1581 \sa setSocketDescriptor()
1583 int QAbstractSocket::socketDescriptor() const
1585 Q_D(const QAbstractSocket);
1586 return d->cachedSocketDescriptor;
1590 Initializes QAbstractSocket with the native socket descriptor \a
1591 socketDescriptor. Returns true if \a socketDescriptor is accepted
1592 as a valid socket descriptor; otherwise returns false.
1593 The socket is opened in the mode specified by \a openMode, and
1594 enters the socket state specified by \a socketState.
1596 \bold{Note:} It is not possible to initialize two abstract sockets
1597 with the same native socket descriptor.
1599 \sa socketDescriptor()
1601 bool QAbstractSocket::setSocketDescriptor(int socketDescriptor, SocketState socketState,
1604 Q_D(QAbstractSocket);
1605 #ifndef QT_NO_OPENSSL
1606 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
1607 return socket->setSocketDescriptor(socketDescriptor, socketState, openMode);
1610 d->resetSocketLayer();
1611 d->socketEngine = QAbstractSocketEngine::createSocketEngine(socketDescriptor, this);
1612 if (!d->socketEngine) {
1613 d->socketError = UnsupportedSocketOperationError;
1614 setErrorString(tr("Operation on socket is not supported"));
1617 #ifndef QT_NO_BEARERMANAGEMENT
1618 //copy network session down to the socket engine (if it has been set)
1619 d->socketEngine->setProperty("_q_networksession", property("_q_networksession"));
1621 bool result = d->socketEngine->initialize(socketDescriptor, socketState);
1623 d->socketError = d->socketEngine->error();
1624 setErrorString(d->socketEngine->errorString());
1628 if (d->threadData->eventDispatcher)
1629 d->socketEngine->setReceiver(d);
1631 QIODevice::open(openMode);
1633 if (d->state != socketState) {
1634 d->state = socketState;
1635 emit stateChanged(d->state);
1638 d->pendingClose = false;
1639 d->socketEngine->setReadNotificationEnabled(true);
1640 d->localPort = d->socketEngine->localPort();
1641 d->peerPort = d->socketEngine->peerPort();
1642 d->localAddress = d->socketEngine->localAddress();
1643 d->peerAddress = d->socketEngine->peerAddress();
1644 d->cachedSocketDescriptor = socketDescriptor;
1651 Sets the given \a option to the value described by \a value.
1655 void QAbstractSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
1657 #ifndef QT_NO_OPENSSL
1658 if (QSslSocket *sslSocket = qobject_cast<QSslSocket*>(this)) {
1659 sslSocket->setSocketOption(option, value);
1664 if (!d_func()->socketEngine)
1668 case LowDelayOption:
1669 d_func()->socketEngine->setOption(QAbstractSocketEngine::LowDelayOption, value.toInt());
1672 case KeepAliveOption:
1673 d_func()->socketEngine->setOption(QAbstractSocketEngine::KeepAliveOption, value.toInt());
1676 case MulticastTtlOption:
1677 d_func()->socketEngine->setOption(QAbstractSocketEngine::MulticastTtlOption, value.toInt());
1680 case MulticastLoopbackOption:
1681 d_func()->socketEngine->setOption(QAbstractSocketEngine::MulticastLoopbackOption, value.toInt());
1688 Returns the value of the \a option option.
1690 \sa setSocketOption()
1692 QVariant QAbstractSocket::socketOption(QAbstractSocket::SocketOption option)
1694 #ifndef QT_NO_OPENSSL
1695 if (QSslSocket *sslSocket = qobject_cast<QSslSocket*>(this)) {
1696 return sslSocket->socketOption(option);
1700 if (!d_func()->socketEngine)
1705 case LowDelayOption:
1706 ret = d_func()->socketEngine->option(QAbstractSocketEngine::LowDelayOption);
1709 case KeepAliveOption:
1710 ret = d_func()->socketEngine->option(QAbstractSocketEngine::KeepAliveOption);
1713 case MulticastTtlOption:
1714 ret = d_func()->socketEngine->option(QAbstractSocketEngine::MulticastTtlOption);
1716 case MulticastLoopbackOption:
1717 ret = d_func()->socketEngine->option(QAbstractSocketEngine::MulticastLoopbackOption);
1723 return QVariant(ret);
1728 Returns the difference between msecs and elapsed. If msecs is -1,
1729 however, -1 is returned.
1731 static int qt_timeout_value(int msecs, int elapsed)
1736 int timeout = msecs - elapsed;
1737 return timeout < 0 ? 0 : timeout;
1741 Waits until the socket is connected, up to \a msecs
1742 milliseconds. If the connection has been established, this
1743 function returns true; otherwise it returns false. In the case
1744 where it returns false, you can call error() to determine
1745 the cause of the error.
1747 The following example waits up to one second for a connection
1750 \snippet doc/src/snippets/code/src_network_socket_qabstractsocket.cpp 0
1752 If msecs is -1, this function will not time out.
1754 \note This function may wait slightly longer than \a msecs,
1755 depending on the time it takes to complete the host lookup.
1757 \note Multiple calls to this functions do not accumulate the time.
1758 If the function times out, the connecting process will be aborted.
1760 \sa connectToHost(), connected()
1762 bool QAbstractSocket::waitForConnected(int msecs)
1764 Q_D(QAbstractSocket);
1765 #if defined (QABSTRACTSOCKET_DEBUG)
1766 qDebug("QAbstractSocket::waitForConnected(%i)", msecs);
1769 if (state() == ConnectedState) {
1770 #if defined (QABSTRACTSOCKET_DEBUG)
1771 qDebug("QAbstractSocket::waitForConnected(%i) already connected", msecs);
1776 #ifndef QT_NO_OPENSSL
1777 // Manual polymorphism; this function is not virtual, but has an overload
1779 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
1780 return socket->waitForConnected(msecs);
1783 bool wasPendingClose = d->pendingClose;
1784 d->pendingClose = false;
1785 QElapsedTimer stopWatch;
1788 if (d->state == HostLookupState) {
1789 #if defined (QABSTRACTSOCKET_DEBUG)
1790 qDebug("QAbstractSocket::waitForConnected(%i) doing host name lookup", msecs);
1792 QHostInfo::abortHostLookup(d->hostLookupId);
1793 d->hostLookupId = -1;
1794 #ifndef QT_NO_BEARERMANAGEMENT
1795 QSharedPointer<QNetworkSession> networkSession;
1796 QVariant v(property("_q_networksession"));
1798 networkSession = qvariant_cast< QSharedPointer<QNetworkSession> >(v);
1799 d->_q_startConnecting(QHostInfoPrivate::fromName(d->hostName, networkSession));
1802 d->_q_startConnecting(QHostInfo::fromName(d->hostName));
1804 if (state() == UnconnectedState)
1805 return false; // connect not im progress anymore!
1807 bool timedOut = true;
1808 #if defined (QABSTRACTSOCKET_DEBUG)
1811 while (state() == ConnectingState && (msecs == -1 || stopWatch.elapsed() < msecs)) {
1812 int timeout = qt_timeout_value(msecs, stopWatch.elapsed());
1813 if (msecs != -1 && timeout > QT_CONNECT_TIMEOUT)
1814 timeout = QT_CONNECT_TIMEOUT;
1815 #if defined (QABSTRACTSOCKET_DEBUG)
1816 qDebug("QAbstractSocket::waitForConnected(%i) waiting %.2f secs for connection attempt #%i",
1817 msecs, timeout / 1000.0, attempt++);
1821 if (d->socketEngine && d->socketEngine->waitForWrite(timeout, &timedOut) && !timedOut) {
1822 d->_q_testConnection();
1824 d->_q_connectToNextAddress();
1828 if ((timedOut && state() != ConnectedState) || state() == ConnectingState) {
1829 d->socketError = SocketTimeoutError;
1830 d->state = UnconnectedState;
1831 emit stateChanged(d->state);
1832 d->resetSocketLayer();
1833 setErrorString(tr("Socket operation timed out"));
1836 #if defined (QABSTRACTSOCKET_DEBUG)
1837 qDebug("QAbstractSocket::waitForConnected(%i) == %s", msecs,
1838 state() == ConnectedState ? "true" : "false");
1840 if (state() != ConnectedState)
1842 if (wasPendingClose)
1843 disconnectFromHost();
1848 This function blocks until new data is available for reading and the
1849 \l{QIODevice::}{readyRead()} signal has been emitted. The function
1850 will timeout after \a msecs milliseconds; the default timeout is
1853 The function returns true if the readyRead() signal is emitted and
1854 there is new data available for reading; otherwise it returns false
1855 (if an error occurred or the operation timed out).
1857 \sa waitForBytesWritten()
1859 bool QAbstractSocket::waitForReadyRead(int msecs)
1861 Q_D(QAbstractSocket);
1862 #if defined (QABSTRACTSOCKET_DEBUG)
1863 qDebug("QAbstractSocket::waitForReadyRead(%i)", msecs);
1866 // require calling connectToHost() before waitForReadyRead()
1867 if (state() == UnconnectedState) {
1868 /* If all you have is a QIODevice pointer to an abstractsocket, you cannot check
1869 this, so you cannot avoid this warning. */
1870 // qWarning("QAbstractSocket::waitForReadyRead() is not allowed in UnconnectedState");
1874 QElapsedTimer stopWatch;
1877 // handle a socket in connecting state
1878 if (state() == HostLookupState || state() == ConnectingState) {
1879 if (!waitForConnected(msecs))
1883 Q_ASSERT(d->socketEngine);
1885 bool readyToRead = false;
1886 bool readyToWrite = false;
1887 if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
1888 qt_timeout_value(msecs, stopWatch.elapsed()))) {
1889 d->socketError = d->socketEngine->error();
1890 setErrorString(d->socketEngine->errorString());
1891 #if defined (QABSTRACTSOCKET_DEBUG)
1892 qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
1893 msecs, d->socketError, errorString().toLatin1().constData());
1895 emit error(d->socketError);
1896 if (d->socketError != SocketTimeoutError)
1902 if (d->canReadNotification())
1907 d->canWriteNotification();
1909 if (state() != ConnectedState)
1911 } while (msecs == -1 || qt_timeout_value(msecs, stopWatch.elapsed()) > 0);
1917 bool QAbstractSocket::waitForBytesWritten(int msecs)
1919 Q_D(QAbstractSocket);
1920 #if defined (QABSTRACTSOCKET_DEBUG)
1921 qDebug("QAbstractSocket::waitForBytesWritten(%i)", msecs);
1924 // require calling connectToHost() before waitForBytesWritten()
1925 if (state() == UnconnectedState) {
1926 qWarning("QAbstractSocket::waitForBytesWritten() is not allowed in UnconnectedState");
1930 if (d->writeBuffer.isEmpty())
1933 QElapsedTimer stopWatch;
1936 // handle a socket in connecting state
1937 if (state() == HostLookupState || state() == ConnectingState) {
1938 if (!waitForConnected(msecs))
1943 bool readyToRead = false;
1944 bool readyToWrite = false;
1945 if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
1946 qt_timeout_value(msecs, stopWatch.elapsed()))) {
1947 d->socketError = d->socketEngine->error();
1948 setErrorString(d->socketEngine->errorString());
1949 #if defined (QABSTRACTSOCKET_DEBUG)
1950 qDebug("QAbstractSocket::waitForBytesWritten(%i) failed (%i, %s)",
1951 msecs, d->socketError, errorString().toLatin1().constData());
1953 emit error(d->socketError);
1954 if (d->socketError != SocketTimeoutError)
1960 #if defined (QABSTRACTSOCKET_DEBUG)
1961 qDebug("QAbstractSocket::waitForBytesWritten calls canReadNotification");
1963 if(!d->canReadNotification())
1969 if (d->canWriteNotification()) {
1970 #if defined (QABSTRACTSOCKET_DEBUG)
1971 qDebug("QAbstractSocket::waitForBytesWritten returns true");
1977 if (state() != ConnectedState)
1984 Waits until the socket has disconnected, up to \a msecs
1985 milliseconds. If the connection has been disconnected, this
1986 function returns true; otherwise it returns false. In the case
1987 where it returns false, you can call error() to determine
1988 the cause of the error.
1990 The following example waits up to one second for a connection
1993 \snippet doc/src/snippets/code/src_network_socket_qabstractsocket.cpp 1
1995 If msecs is -1, this function will not time out.
1997 \sa disconnectFromHost(), close()
1999 bool QAbstractSocket::waitForDisconnected(int msecs)
2001 Q_D(QAbstractSocket);
2002 #ifndef QT_NO_OPENSSL
2003 // Manual polymorphism; this function is not virtual, but has an overload
2005 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
2006 return socket->waitForDisconnected(msecs);
2009 // require calling connectToHost() before waitForDisconnected()
2010 if (state() == UnconnectedState) {
2011 qWarning("QAbstractSocket::waitForDisconnected() is not allowed in UnconnectedState");
2015 QElapsedTimer stopWatch;
2018 // handle a socket in connecting state
2019 if (state() == HostLookupState || state() == ConnectingState) {
2020 if (!waitForConnected(msecs))
2022 if (state() == UnconnectedState)
2027 bool readyToRead = false;
2028 bool readyToWrite = false;
2029 if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, state() == ConnectedState,
2030 !d->writeBuffer.isEmpty(),
2031 qt_timeout_value(msecs, stopWatch.elapsed()))) {
2032 d->socketError = d->socketEngine->error();
2033 setErrorString(d->socketEngine->errorString());
2034 #if defined (QABSTRACTSOCKET_DEBUG)
2035 qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
2036 msecs, d->socketError, errorString().toLatin1().constData());
2038 emit error(d->socketError);
2039 if (d->socketError != SocketTimeoutError)
2045 d->canReadNotification();
2047 d->canWriteNotification();
2049 if (state() == UnconnectedState)
2056 Aborts the current connection and resets the socket. Unlike disconnectFromHost(),
2057 this function immediately closes the socket, discarding any pending data in the
2060 \sa disconnectFromHost(), close()
2062 void QAbstractSocket::abort()
2064 Q_D(QAbstractSocket);
2065 #if defined (QABSTRACTSOCKET_DEBUG)
2066 qDebug("QAbstractSocket::abort()");
2068 if (d->state == UnconnectedState)
2070 #ifndef QT_NO_OPENSSL
2071 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this)) {
2076 if (d->connectTimer) {
2077 d->connectTimer->stop();
2078 delete d->connectTimer;
2079 d->connectTimer = 0;
2082 d->writeBuffer.clear();
2083 d->abortCalled = true;
2089 bool QAbstractSocket::isSequential() const
2096 Returns true if no more data is currently
2097 available for reading; otherwise returns false.
2099 This function is most commonly used when reading data from the
2100 socket in a loop. For example:
2102 \snippet doc/src/snippets/code/src_network_socket_qabstractsocket.cpp 2
2104 \sa bytesAvailable(), readyRead()
2106 bool QAbstractSocket::atEnd() const
2108 return QIODevice::atEnd() && (!isOpen() || d_func()->readBuffer.isEmpty());
2112 This function writes as much as possible from the internal write buffer to
2113 the underlying network socket, without blocking. If any data was written,
2114 this function returns true; otherwise false is returned.
2116 Call this function if you need QAbstractSocket to start sending buffered
2117 data immediately. The number of bytes successfully written depends on the
2118 operating system. In most cases, you do not need to call this function,
2119 because QAbstractSocket will start sending data automatically once control
2120 goes back to the event loop. In the absence of an event loop, call
2121 waitForBytesWritten() instead.
2123 \sa write(), waitForBytesWritten()
2125 // Note! docs copied to QSslSocket::flush()
2126 bool QAbstractSocket::flush()
2128 Q_D(QAbstractSocket);
2129 #ifndef QT_NO_OPENSSL
2130 // Manual polymorphism; flush() isn't virtual, but QSslSocket overloads
2132 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
2133 return socket->flush();
2135 Q_CHECK_SOCKETENGINE(false);
2141 qint64 QAbstractSocket::readData(char *data, qint64 maxSize)
2143 Q_D(QAbstractSocket);
2145 // This is for a buffered QTcpSocket
2146 if (d->isBuffered && d->readBuffer.isEmpty())
2147 // if we're still connected, return 0 indicating there may be more data in the future
2148 // if we're not connected, return -1 indicating EOF
2149 return d->state == QAbstractSocket::ConnectedState ? qint64(0) : qint64(-1);
2151 // short cut for a char read if we have something in the buffer
2152 if (maxSize == 1 && !d->readBuffer.isEmpty()) {
2153 *data = d->readBuffer.getChar();
2154 #if defined (QABSTRACTSOCKET_DEBUG)
2155 qDebug("QAbstractSocket::readData(%p '%c (0x%.2x)', 1) == 1 [char buffer]",
2156 data, isprint(int(uchar(*data))) ? *data : '?', *data);
2158 if (d->readBuffer.isEmpty() && d->socketEngine && d->socketEngine->isValid())
2159 d->socketEngine->setReadNotificationEnabled(true);
2163 // Special case for an Unbuffered QTcpSocket
2164 // Re-filling the buffer.
2165 if (d->socketType == TcpSocket
2167 && d->readBuffer.size() < maxSize
2168 && d->readBufferMaxSize > 0
2169 && maxSize < d->readBufferMaxSize
2171 && d->socketEngine->isValid()) {
2172 // Our buffer is empty and a read() was requested for a byte amount that is smaller
2173 // than the readBufferMaxSize. This means that we should fill our buffer since we want
2174 // such small reads come from the buffer and not always go to the costly socket engine read()
2175 qint64 bytesToRead = d->socketEngine->bytesAvailable();
2176 if (bytesToRead > 0) {
2177 char *ptr = d->readBuffer.reserve(bytesToRead);
2178 qint64 readBytes = d->socketEngine->read(ptr, bytesToRead);
2179 if (readBytes == -2) {
2180 // No bytes currently available for reading.
2181 d->readBuffer.chop(bytesToRead);
2183 d->readBuffer.chop(int(bytesToRead - (readBytes < 0 ? qint64(0) : readBytes)));
2188 // First try to satisfy the read from the buffer
2189 qint64 bytesToRead = qMin(qint64(d->readBuffer.size()), maxSize);
2190 qint64 readSoFar = 0;
2191 while (readSoFar < bytesToRead) {
2192 const char *ptr = d->readBuffer.readPointer();
2193 int bytesToReadFromThisBlock = qMin(int(bytesToRead - readSoFar),
2194 d->readBuffer.nextDataBlockSize());
2195 memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
2196 readSoFar += bytesToReadFromThisBlock;
2197 d->readBuffer.free(bytesToReadFromThisBlock);
2200 if (d->socketEngine && !d->socketEngine->isReadNotificationEnabled() && d->socketEngine->isValid())
2201 d->socketEngine->setReadNotificationEnabled(true);
2203 if (readSoFar > 0) {
2204 // we read some data from buffer.
2205 // Just return, readyRead will be emitted again
2206 #if defined (QABSTRACTSOCKET_DEBUG)
2207 qDebug("QAbstractSocket::readData(%p '%c (0x%.2x)', %lli) == %lli [buffer]",
2208 data, isprint(int(uchar(*data))) ? *data : '?', *data, maxSize, readSoFar);
2211 if (d->readBuffer.isEmpty() && d->socketEngine)
2212 d->socketEngine->setReadNotificationEnabled(true);
2216 // This code path is for Unbuffered QTcpSocket or for connected UDP
2218 if (!d->isBuffered) {
2219 if (!d->socketEngine)
2220 return -1; // no socket engine is probably EOF
2221 if (!d->socketEngine->isValid())
2222 return -1; // This is for unbuffered TCP when we already had been disconnected
2223 if (d->state != QAbstractSocket::ConnectedState)
2224 return -1; // This is for unbuffered TCP if we're not connected yet
2225 qint64 readBytes = d->socketEngine->read(data, maxSize);
2226 if (readBytes == -2) {
2227 // -2 from the engine means no bytes available (EAGAIN) so read more later
2229 } else if (readBytes < 0) {
2230 d->socketError = d->socketEngine->error();
2231 setErrorString(d->socketEngine->errorString());
2232 d->resetSocketLayer();
2233 d->state = QAbstractSocket::UnconnectedState;
2234 } else if (!d->socketEngine->isReadNotificationEnabled()) {
2235 // Only do this when there was no error
2236 d->socketEngine->setReadNotificationEnabled(true);
2239 #if defined (QABSTRACTSOCKET_DEBUG)
2240 qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld [engine]",
2241 data, qt_prettyDebug(data, 32, readBytes).data(), maxSize,
2248 #if defined (QABSTRACTSOCKET_DEBUG)
2249 qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld [unreachable]",
2250 data, qt_prettyDebug(data, qMin<qint64>(32, readSoFar), readSoFar).data(),
2251 maxSize, readSoFar);
2258 qint64 QAbstractSocket::readLineData(char *data, qint64 maxlen)
2260 return QIODevice::readLineData(data, maxlen);
2265 qint64 QAbstractSocket::writeData(const char *data, qint64 size)
2267 Q_D(QAbstractSocket);
2268 if (d->state == QAbstractSocket::UnconnectedState) {
2269 d->socketError = QAbstractSocket::UnknownSocketError;
2270 setErrorString(tr("Socket is not connected"));
2274 if (!d->isBuffered && d->socketType == TcpSocket && d->writeBuffer.isEmpty()) {
2275 // This code is for the new Unbuffered QTcpSocket use case
2276 qint64 written = d->socketEngine->write(data, size);
2278 d->socketError = d->socketEngine->error();
2279 setErrorString(d->socketEngine->errorString());
2281 } else if (written < size) {
2282 // Buffer what was not written yet
2283 char *ptr = d->writeBuffer.reserve(size - written);
2284 memcpy(ptr, data + written, size - written);
2285 if (d->socketEngine)
2286 d->socketEngine->setWriteNotificationEnabled(true);
2288 return size; // size=actually written + what has been buffered
2289 } else if (!d->isBuffered && d->socketType != TcpSocket) {
2290 // This is for a QUdpSocket that was connect()ed
2291 qint64 written = d->socketEngine->write(data, size);
2293 d->socketError = d->socketEngine->error();
2294 setErrorString(d->socketEngine->errorString());
2295 } else if (!d->writeBuffer.isEmpty()) {
2296 d->socketEngine->setWriteNotificationEnabled(true);
2299 #if defined (QABSTRACTSOCKET_DEBUG)
2300 qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2301 qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2305 emit bytesWritten(written);
2309 // This is the code path for normal buffered QTcpSocket or
2310 // unbuffered QTcpSocket when there was already something in the
2311 // write buffer and therefore we could not do a direct engine write.
2312 // We just write to our write buffer and enable the write notifier
2313 // The write notifier then flush()es the buffer.
2315 char *ptr = d->writeBuffer.reserve(size);
2319 memcpy(ptr, data, size);
2321 qint64 written = size;
2323 if (d->socketEngine && !d->writeBuffer.isEmpty())
2324 d->socketEngine->setWriteNotificationEnabled(true);
2326 #if defined (QABSTRACTSOCKET_DEBUG)
2327 qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2328 qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2337 Sets the port on the local side of a connection to \a port.
2339 You can call this function in a subclass of QAbstractSocket to
2340 change the return value of the localPort() function after a
2341 connection has been established. This feature is commonly used by
2342 proxy connections for virtual connection settings.
2344 Note that this function does not bind the local port of the socket
2345 prior to a connection (e.g., QUdpSocket::bind()).
2347 \sa localAddress(), setLocalAddress(), setPeerPort()
2349 void QAbstractSocket::setLocalPort(quint16 port)
2351 Q_D(QAbstractSocket);
2352 d->localPort = port;
2358 Sets the address on the local side of a connection to
2361 You can call this function in a subclass of QAbstractSocket to
2362 change the return value of the localAddress() function after a
2363 connection has been established. This feature is commonly used by
2364 proxy connections for virtual connection settings.
2366 Note that this function does not bind the local address of the socket
2367 prior to a connection (e.g., QUdpSocket::bind()).
2369 \sa localAddress(), setLocalPort(), setPeerAddress()
2371 void QAbstractSocket::setLocalAddress(const QHostAddress &address)
2373 Q_D(QAbstractSocket);
2374 d->localAddress = address;
2380 Sets the port of the remote side of the connection to
2383 You can call this function in a subclass of QAbstractSocket to
2384 change the return value of the peerPort() function after a
2385 connection has been established. This feature is commonly used by
2386 proxy connections for virtual connection settings.
2388 \sa peerPort(), setPeerAddress(), setLocalPort()
2390 void QAbstractSocket::setPeerPort(quint16 port)
2392 Q_D(QAbstractSocket);
2399 Sets the address of the remote side of the connection
2402 You can call this function in a subclass of QAbstractSocket to
2403 change the return value of the peerAddress() function after a
2404 connection has been established. This feature is commonly used by
2405 proxy connections for virtual connection settings.
2407 \sa peerAddress(), setPeerPort(), setLocalAddress()
2409 void QAbstractSocket::setPeerAddress(const QHostAddress &address)
2411 Q_D(QAbstractSocket);
2412 d->peerAddress = address;
2418 Sets the host name of the remote peer to \a name.
2420 You can call this function in a subclass of QAbstractSocket to
2421 change the return value of the peerName() function after a
2422 connection has been established. This feature is commonly used by
2423 proxy connections for virtual connection settings.
2427 void QAbstractSocket::setPeerName(const QString &name)
2429 Q_D(QAbstractSocket);
2434 Closes the I/O device for the socket, disconnects the socket's connection with the
2435 host, closes the socket, and resets the name, address, port number and underlying
2438 See QIODevice::close() for a description of the actions that occur when an I/O
2443 void QAbstractSocket::close()
2445 Q_D(QAbstractSocket);
2446 #if defined(QABSTRACTSOCKET_DEBUG)
2447 qDebug("QAbstractSocket::close()");
2450 if (d->state != UnconnectedState) {
2451 d->closeCalled = true;
2452 disconnectFromHost();
2457 d->localAddress.clear();
2458 d->peerAddress.clear();
2459 d->peerName.clear();
2460 d->cachedSocketDescriptor = -1;
2464 Attempts to close the socket. If there is pending data waiting to
2465 be written, QAbstractSocket will enter ClosingState and wait
2466 until all data has been written. Eventually, it will enter
2467 UnconnectedState and emit the disconnected() signal.
2471 void QAbstractSocket::disconnectFromHost()
2473 QMetaObject::invokeMethod(this, "disconnectFromHostImplementation",
2474 Qt::DirectConnection);
2480 Contains the implementation of disconnectFromHost().
2482 void QAbstractSocket::disconnectFromHostImplementation()
2484 Q_D(QAbstractSocket);
2485 #if defined(QABSTRACTSOCKET_DEBUG)
2486 qDebug("QAbstractSocket::disconnectFromHost()");
2489 if (d->state == UnconnectedState) {
2490 #if defined(QABSTRACTSOCKET_DEBUG)
2491 qDebug("QAbstractSocket::disconnectFromHost() was called on an unconnected socket");
2496 if (!d->abortCalled && (d->state == ConnectingState || d->state == HostLookupState)) {
2497 #if defined(QABSTRACTSOCKET_DEBUG)
2498 qDebug("QAbstractSocket::disconnectFromHost() but we're still connecting");
2500 d->pendingClose = true;
2505 emit connectionClosed(); // compat signal
2508 // Disable and delete read notification
2509 if (d->socketEngine)
2510 d->socketEngine->setReadNotificationEnabled(false);
2512 if (d->abortCalled) {
2513 #if defined(QABSTRACTSOCKET_DEBUG)
2514 qDebug("QAbstractSocket::disconnectFromHost() aborting immediately");
2516 if (d->state == HostLookupState) {
2517 QHostInfo::abortHostLookup(d->hostLookupId);
2518 d->hostLookupId = -1;
2521 // Perhaps emit closing()
2522 if (d->state != ClosingState) {
2523 d->state = ClosingState;
2524 #if defined(QABSTRACTSOCKET_DEBUG)
2525 qDebug("QAbstractSocket::disconnectFromHost() emits stateChanged()(ClosingState)");
2527 emit stateChanged(d->state);
2529 #if defined(QABSTRACTSOCKET_DEBUG)
2530 qDebug("QAbstractSocket::disconnectFromHost() return from delayed close");
2534 // Wait for pending data to be written.
2535 if (d->socketEngine && d->socketEngine->isValid() && (d->writeBuffer.size() > 0
2536 || d->socketEngine->bytesToWrite() > 0)) {
2537 // hack: when we are waiting for the socket engine to write bytes (only
2538 // possible when using Socks5 or HTTP socket engine), then close
2539 // anyway after 2 seconds. This is to prevent a timeout on Mac, where we
2540 // sometimes just did not get the write notifier from the underlying
2541 // CFSocket and no progress was made.
2542 if (d->writeBuffer.size() == 0 && d->socketEngine->bytesToWrite() > 0) {
2543 if (!d->disconnectTimer) {
2544 d->disconnectTimer = new QTimer(this);
2545 connect(d->disconnectTimer, SIGNAL(timeout()), this,
2546 SLOT(_q_forceDisconnect()), Qt::DirectConnection);
2548 if (!d->disconnectTimer->isActive())
2549 d->disconnectTimer->start(2000);
2551 d->socketEngine->setWriteNotificationEnabled(true);
2553 #if defined(QABSTRACTSOCKET_DEBUG)
2554 qDebug("QAbstractSocket::disconnectFromHost() delaying disconnect");
2558 #if defined(QABSTRACTSOCKET_DEBUG)
2559 qDebug("QAbstractSocket::disconnectFromHost() disconnecting immediately");
2564 SocketState previousState = d->state;
2565 d->resetSocketLayer();
2566 d->state = UnconnectedState;
2567 emit stateChanged(d->state);
2568 emit readChannelFinished(); // we got an EOF
2571 emit delayedCloseFinished(); // compat signal
2573 // only emit disconnected if we were connected before
2574 if (previousState == ConnectedState || previousState == ClosingState)
2575 emit disconnected();
2579 d->localAddress.clear();
2580 d->peerAddress.clear();
2582 #if defined(QABSTRACTSOCKET_DEBUG)
2583 qDebug("QAbstractSocket::disconnectFromHost() disconnected!");
2586 if (d->closeCalled) {
2587 #if defined(QABSTRACTSOCKET_DEBUG)
2588 qDebug("QAbstractSocket::disconnectFromHost() closed!");
2590 d->readBuffer.clear();
2591 d->writeBuffer.clear();
2597 Returns the size of the internal read buffer. This limits the
2598 amount of data that the client can receive before you call read()
2601 A read buffer size of 0 (the default) means that the buffer has
2602 no size limit, ensuring that no data is lost.
2604 \sa setReadBufferSize(), read()
2606 qint64 QAbstractSocket::readBufferSize() const
2608 return d_func()->readBufferMaxSize;
2612 Sets the size of QAbstractSocket's internal read buffer to be \a
2615 If the buffer size is limited to a certain size, QAbstractSocket
2616 won't buffer more than this size of data. Exceptionally, a buffer
2617 size of 0 means that the read buffer is unlimited and all
2618 incoming data is buffered. This is the default.
2620 This option is useful if you only read the data at certain points
2621 in time (e.g., in a real-time streaming application) or if you
2622 want to protect your socket against receiving too much data,
2623 which may eventually cause your application to run out of memory.
2625 Only QTcpSocket uses QAbstractSocket's internal buffer; QUdpSocket
2626 does not use any buffering at all, but rather relies on the
2627 implicit buffering provided by the operating system.
2628 Because of this, calling this function on QUdpSocket has no
2631 \sa readBufferSize(), read()
2633 void QAbstractSocket::setReadBufferSize(qint64 size)
2635 Q_D(QAbstractSocket);
2637 #ifndef QT_NO_OPENSSL
2638 // Manual polymorphism; setReadBufferSize() isn't virtual, but QSslSocket overloads
2640 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this)) {
2641 socket->setReadBufferSize(size);
2646 if (d->readBufferMaxSize == size)
2648 d->readBufferMaxSize = size;
2649 if (!d->readSocketNotifierCalled && d->socketEngine) {
2650 // ensure that the read notification is enabled if we've now got
2651 // room in the read buffer
2652 // but only if we're not inside canReadNotification -- that will take care on its own
2653 if ((size == 0 || d->readBuffer.size() < size) && d->state == QAbstractSocket::ConnectedState) // Do not change the notifier unless we are connected.
2654 d->socketEngine->setReadNotificationEnabled(true);
2659 Returns the state of the socket.
2663 QAbstractSocket::SocketState QAbstractSocket::state() const
2665 return d_func()->state;
2669 Sets the state of the socket to \a state.
2673 void QAbstractSocket::setSocketState(SocketState state)
2675 d_func()->state = state;
2679 Returns the socket type (TCP, UDP, or other).
2681 \sa QTcpSocket, QUdpSocket
2683 QAbstractSocket::SocketType QAbstractSocket::socketType() const
2685 return d_func()->socketType;
2689 Returns the type of error that last occurred.
2691 \sa state(), errorString()
2693 QAbstractSocket::SocketError QAbstractSocket::error() const
2695 return d_func()->socketError;
2699 Sets the type of error that last occurred to \a socketError.
2701 \sa setSocketState(), setErrorString()
2703 void QAbstractSocket::setSocketError(SocketError socketError)
2705 d_func()->socketError = socketError;
2708 #ifndef QT_NO_NETWORKPROXY
2712 Sets the explicit network proxy for this socket to \a networkProxy.
2714 To disable the use of a proxy for this socket, use the
2715 QNetworkProxy::NoProxy proxy type:
2717 \snippet doc/src/snippets/code/src_network_socket_qabstractsocket.cpp 3
2719 The default value for the proxy is QNetworkProxy::DefaultProxy,
2720 which means the socket will use the application settings: if a
2721 proxy is set with QNetworkProxy::setApplicationProxy, it will use
2722 that; otherwise, if a factory is set with
2723 QNetworkProxyFactory::setApplicationProxyFactory, it will query
2724 that factory with type QNetworkProxyQuery::TcpSocket.
2726 \sa proxy(), QNetworkProxy, QNetworkProxyFactory::queryProxy()
2728 void QAbstractSocket::setProxy(const QNetworkProxy &networkProxy)
2730 Q_D(QAbstractSocket);
2731 d->proxy = networkProxy;
2737 Returns the network proxy for this socket.
2738 By default QNetworkProxy::DefaultProxy is used, which means this
2739 socket will query the default proxy settings for the application.
2741 \sa setProxy(), QNetworkProxy, QNetworkProxyFactory
2743 QNetworkProxy QAbstractSocket::proxy() const
2745 Q_D(const QAbstractSocket);
2748 #endif // QT_NO_NETWORKPROXY
2752 \enum QAbstractSocket::Error
2755 Use QAbstractSocket::SocketError instead.
2757 \value ErrConnectionRefused Use QAbstractSocket::ConnectionRefusedError instead.
2758 \value ErrHostNotFound Use QAbstractSocket::HostNotFoundError instead.
2759 \value ErrSocketRead Use QAbstractSocket::UnknownSocketError instead.
2763 \typedef QAbstractSocket::State
2766 Use QAbstractSocket::SocketState instead.
2769 \header \o Qt 3 enum value \o Qt 4 enum value
2770 \row \o \c Idle \o \l UnconnectedState
2771 \row \o \c HostLookup \o \l HostLookupState
2772 \row \o \c Connecting \o \l ConnectingState
2773 \row \o \c Connected \o \l ConnectedState
2774 \row \o \c Closing \o \l ClosingState
2775 \row \o \c Connection \o \l ConnectedState
2780 \fn int QAbstractSocket::socket() const
2782 Use socketDescriptor() instead.
2786 \fn void QAbstractSocket::setSocket(int socket)
2788 Use setSocketDescriptor() instead.
2792 \fn Q_ULONG QAbstractSocket::waitForMore(int msecs, bool *timeout = 0) const
2794 Use waitForReadyRead() instead.
2798 Q_ULONG numBytes = socket->waitForMore(30000, &timeout);
2800 qint64 numBytes = 0;
2801 if (socket->waitForReadyRead(msecs))
2802 numBytes = socket->bytesAvailable();
2803 bool timeout = (error() == QAbstractSocket::SocketTimeoutError);
2806 \sa waitForReadyRead(), bytesAvailable(), error(), SocketTimeoutError
2810 \fn void QAbstractSocket::connectionClosed()
2812 Use disconnected() instead.
2816 \fn void QAbstractSocket::delayedCloseFinished()
2818 Use disconnected() instead.
2820 #endif // QT3_SUPPORT
2822 #ifndef QT_NO_DEBUG_STREAM
2823 Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketError error)
2826 case QAbstractSocket::ConnectionRefusedError:
2827 debug << "QAbstractSocket::ConnectionRefusedError";
2829 case QAbstractSocket::RemoteHostClosedError:
2830 debug << "QAbstractSocket::RemoteHostClosedError";
2832 case QAbstractSocket::HostNotFoundError:
2833 debug << "QAbstractSocket::HostNotFoundError";
2835 case QAbstractSocket::SocketAccessError:
2836 debug << "QAbstractSocket::SocketAccessError";
2838 case QAbstractSocket::SocketResourceError:
2839 debug << "QAbstractSocket::SocketResourceError";
2841 case QAbstractSocket::SocketTimeoutError:
2842 debug << "QAbstractSocket::SocketTimeoutError";
2844 case QAbstractSocket::DatagramTooLargeError:
2845 debug << "QAbstractSocket::DatagramTooLargeError";
2847 case QAbstractSocket::NetworkError:
2848 debug << "QAbstractSocket::NetworkError";
2850 case QAbstractSocket::AddressInUseError:
2851 debug << "QAbstractSocket::AddressInUseError";
2853 case QAbstractSocket::SocketAddressNotAvailableError:
2854 debug << "QAbstractSocket::SocketAddressNotAvailableError";
2856 case QAbstractSocket::UnsupportedSocketOperationError:
2857 debug << "QAbstractSocket::UnsupportedSocketOperationError";
2859 case QAbstractSocket::UnfinishedSocketOperationError:
2860 debug << "QAbstractSocket::UnfinishedSocketOperationError";
2862 case QAbstractSocket::ProxyAuthenticationRequiredError:
2863 debug << "QAbstractSocket::ProxyAuthenticationRequiredError";
2865 case QAbstractSocket::UnknownSocketError:
2866 debug << "QAbstractSocket::UnknownSocketError";
2868 case QAbstractSocket::ProxyConnectionRefusedError:
2869 debug << "QAbstractSocket::ProxyConnectionRefusedError";
2871 case QAbstractSocket::ProxyConnectionClosedError:
2872 debug << "QAbstractSocket::ProxyConnectionClosedError";
2874 case QAbstractSocket::ProxyConnectionTimeoutError:
2875 debug << "QAbstractSocket::ProxyConnectionTimeoutError";
2877 case QAbstractSocket::ProxyNotFoundError:
2878 debug << "QAbstractSocket::ProxyNotFoundError";
2880 case QAbstractSocket::ProxyProtocolError:
2881 debug << "QAbstractSocket::ProxyProtocolError";
2884 debug << "QAbstractSocket::SocketError(" << int(error) << ')';
2890 Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketState state)
2893 case QAbstractSocket::UnconnectedState:
2894 debug << "QAbstractSocket::UnconnectedState";
2896 case QAbstractSocket::HostLookupState:
2897 debug << "QAbstractSocket::HostLookupState";
2899 case QAbstractSocket::ConnectingState:
2900 debug << "QAbstractSocket::ConnectingState";
2902 case QAbstractSocket::ConnectedState:
2903 debug << "QAbstractSocket::ConnectedState";
2905 case QAbstractSocket::BoundState:
2906 debug << "QAbstractSocket::BoundState";
2908 case QAbstractSocket::ListeningState:
2909 debug << "QAbstractSocket::ListeningState";
2911 case QAbstractSocket::ClosingState:
2912 debug << "QAbstractSocket::ClosingState";
2915 debug << "QAbstractSocket::SocketState(" << int(state) << ')';
2924 #include "moc_qabstractsocket.cpp"