1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** 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 \li Instantiate QTcpSocket or QUdpSocket.
60 \li 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. Note that Qt does
99 not limit the write buffer size. You can monitor its size by listening
102 The readyRead() signal is emitted every time a new chunk of data
103 has arrived. bytesAvailable() then returns the number of bytes
104 that are available for reading. Typically, you would connect the
105 readyRead() signal to a slot and read all available data there.
106 If you don't read all the data at once, the remaining data will
107 still be available later, and any new incoming data will be
108 appended to QAbstractSocket's internal read buffer. To limit the
109 size of the read buffer, call setReadBufferSize().
111 To close the socket, call disconnectFromHost(). QAbstractSocket enters
112 QAbstractSocket::ClosingState. After all pending data has been written to
113 the socket, QAbstractSocket actually closes the socket, enters
114 QAbstractSocket::ClosedState, and emits disconnected(). If you want to
115 abort a connection immediately, discarding all pending data, call abort()
116 instead. If the remote host closes the connection, QAbstractSocket will
117 emit error(QAbstractSocket::RemoteHostClosedError), during which the socket
118 state will still be ConnectedState, and then the disconnected() signal
121 The port and address of the connected peer is fetched by calling
122 peerPort() and peerAddress(). peerName() returns the host name of
123 the peer, as passed to connectToHost(). localPort() and
124 localAddress() return the port and address of the local socket.
126 QAbstractSocket provides a set of functions that suspend the
127 calling thread until certain signals are emitted. These functions
128 can be used to implement blocking sockets:
131 \li waitForConnected() blocks until a connection has been established.
133 \li waitForReadyRead() blocks until new data is available for
136 \li waitForBytesWritten() blocks until one payload of data has been
137 written to the socket.
139 \li waitForDisconnected() blocks until the connection has closed.
144 \snippet network/tcpwait.cpp 0
146 If \l{QIODevice::}{waitForReadyRead()} returns false, the
147 connection has been closed or an error has occurred.
149 Programming with a blocking socket is radically different from
150 programming with a non-blocking socket. A blocking socket doesn't
151 require an event loop and typically leads to simpler code.
152 However, in a GUI application, blocking sockets should only be
153 used in non-GUI threads, to avoid freezing the user interface.
154 See the \l network/fortuneclient and \l network/blockingfortuneclient
155 examples for an overview of both approaches.
157 \note We discourage the use of the blocking functions together
158 with signals. One of the two possibilities should be used.
160 QAbstractSocket can be used with QTextStream and QDataStream's
161 stream operators (operator<<() and operator>>()). There is one
162 issue to be aware of, though: You must make sure that enough data
163 is available before attempting to read it using operator>>().
165 \sa QNetworkAccessManager, QTcpServer
169 \fn void QAbstractSocket::hostFound()
171 This signal is emitted after connectToHost() has been called and
172 the host lookup has succeeded.
174 \note Since Qt 4.6.3 QAbstractSocket may emit hostFound()
175 directly from the connectToHost() call since a DNS result could have been
182 \fn void QAbstractSocket::connected()
184 This signal is emitted after connectToHost() has been called and
185 a connection has been successfully established.
187 \note On some operating systems the connected() signal may
188 be directly emitted from the connectToHost() call for connections
191 \sa connectToHost(), disconnected()
195 \fn void QAbstractSocket::disconnected()
197 This signal is emitted when the socket has been disconnected.
199 \warning If you need to delete the sender() of this signal in a slot connected
200 to it, use the \l{QObject::deleteLater()}{deleteLater()} function.
202 \sa connectToHost(), disconnectFromHost(), abort()
206 \fn void QAbstractSocket::error(QAbstractSocket::SocketError socketError)
208 This signal is emitted after an error occurred. The \a socketError
209 parameter describes the type of error that occurred.
211 QAbstractSocket::SocketError is not a registered metatype, so for queued
212 connections, you will have to register it with Q_DECLARE_METATYPE() and
215 \sa error(), errorString(), {Creating Custom Qt Types}
219 \fn void QAbstractSocket::stateChanged(QAbstractSocket::SocketState socketState)
221 This signal is emitted whenever QAbstractSocket's state changes.
222 The \a socketState parameter is the new state.
224 QAbstractSocket::SocketState is not a registered metatype, so for queued
225 connections, you will have to register it with Q_DECLARE_METATYPE() and
228 \sa state(), {Creating Custom Qt Types}
232 \fn void QAbstractSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
235 This signal can be emitted when a \a proxy that requires
236 authentication is used. The \a authenticator object can then be
237 filled in with the required details to allow authentication and
238 continue the connection.
240 \note It is not possible to use a QueuedConnection to connect to
241 this signal, as the connection will fail if the authenticator has
242 not been filled in with new information when the signal returns.
244 \sa QAuthenticator, QNetworkProxy
248 \enum QAbstractSocket::NetworkLayerProtocol
250 This enum describes the network layer protocol values used in Qt.
252 \value IPv4Protocol IPv4
253 \value IPv6Protocol IPv6
254 \value AnyIPProtocol Either IPv4 or 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 QAbstractSocket::bind() is
295 already in use and was set to be exclusive.
296 \value SocketAddressNotAvailableError The address specified to
297 QAbstractSocket::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.
318 \value OperationError An operation was attempted while the socket was in a state that
320 \value SslInternalError The SSL library being used reported a internal error, this is
321 probably the result of a bad installation or misconfiguration of the library.
322 \value SslInvalidUserDataError Invalid data(certificate, key, cypher, etc.) was
323 provided and its use resulted in an error in the SSL library.
325 \value UnknownSocketError An unidentified error occurred.
326 \sa QAbstractSocket::error()
330 \enum QAbstractSocket::SocketState
332 This enum describes the different states in which a socket can be.
334 \value UnconnectedState The socket is not connected.
335 \value HostLookupState The socket is performing a host name lookup.
336 \value ConnectingState The socket has started establishing a connection.
337 \value ConnectedState A connection is established.
338 \value BoundState The socket is bound to an address and port.
339 \value ClosingState The socket is about to close (data may still
340 be waiting to be written).
341 \value ListeningState For internal use only.
343 \sa QAbstractSocket::state()
347 \enum QAbstractSocket::SocketOption
350 This enum represents the options that can be set on a socket. If
351 desired, they can be set after having received the connected()
352 signal from the socket or after having received a new socket from
355 \value LowDelayOption Try to optimize the socket for low
356 latency. For a QTcpSocket this would set the TCP_NODELAY option
357 and disable Nagle's algorithm. Set this to 1 to enable.
359 \value KeepAliveOption Set this to 1 to enable the SO_KEEPALIVE
362 \value MulticastTtlOption Set this to an integer value to set
363 IP_MULTICAST_TTL (TTL for multicast datagrams) socket option.
365 \value MulticastLoopbackOption Set this to 1 to enable the
366 IP_MULTICAST_LOOP (multicast loopback) socket option.
368 \value TypeOfServiceOption This option is not supported on
369 Windows. This maps to to the IP_TOS socket option.
371 Possible values for the \e{TypeOfServiceOption} are:
374 \header \li Value \li Description
375 \row \li 224 \li Network control
376 \row \li 192 \li Internetwork control
377 \row \li 160 \li CRITIC/ECP
378 \row \li 128 \li Flash override
379 \row \li 96 \li Flash
380 \row \li 64 \li Immediate
381 \row \li 32 \li Priority
382 \row \li 0 \li Routine
385 \sa QAbstractSocket::setSocketOption(), QAbstractSocket::socketOption()
388 /*! \enum QAbstractSocket::BindFlag
391 This enum describes the different flags you can pass to modify the
392 behavior of QAbstractSocket::bind().
394 \value ShareAddress Allow other services to bind to the same address
395 and port. This is useful when multiple processes share
396 the load of a single service by listening to the same address and port
397 (e.g., a web server with several pre-forked listeners can greatly
398 improve response time). However, because any service is allowed to
399 rebind, this option is subject to certain security considerations.
400 Note that by combining this option with ReuseAddressHint, you will
401 also allow your service to rebind an existing shared address. On
402 Unix, this is equivalent to the SO_REUSEADDR socket option. On Windows,
403 this option is ignored.
405 \value DontShareAddress Bind the address and port exclusively, so that
406 no other services are allowed to rebind. By passing this option to
407 QAbstractSocket::bind(), you are guaranteed that on successs, your service
408 is the only one that listens to the address and port. No services are
409 allowed to rebind, even if they pass ReuseAddressHint. This option
410 provides more security than ShareAddress, but on certain operating
411 systems, it requires you to run the server with administrator privileges.
412 On Unix and Mac OS X, not sharing is the default behavior for binding
413 an address and port, so this option is ignored. On Windows, this
414 option uses the SO_EXCLUSIVEADDRUSE socket option.
416 \value ReuseAddressHint Provides a hint to QAbstractSocket that it should try
417 to rebind the service even if the address and port are already bound by
418 another socket. On Windows, this is equivalent to the SO_REUSEADDR
419 socket option. On Unix, this option is ignored.
421 \value DefaultForPlatform The default option for the current platform.
422 On Unix and Mac OS X, this is equivalent to (DontShareAddress
423 + ReuseAddressHint), and on Windows, its equivalent to ShareAddress.
426 /*! \enum QAbstractSocket::PauseMode
429 This enum describes the behavior of when the socket should hold
430 back with continuing data transfer.
431 The only notification currently supported is QSslSocket::sslErrors().
433 \value PauseNever Do not pause data transfer on the socket. This is the
434 default and matches the behaviour of Qt 4.
435 \value PauseOnSslErrors Pause data transfer on the socket upon receiving an
436 SSL error notification. I.E. QSslSocket::sslErrors().
439 #include "qabstractsocket.h"
440 #include "qabstractsocket_p.h"
442 #include "private/qhostinfo_p.h"
443 #include "private/qnetworksession_p.h"
445 #include <qabstracteventdispatcher.h>
446 #include <qhostaddress.h>
447 #include <qhostinfo.h>
448 #include <qmetaobject.h>
449 #include <qpointer.h>
451 #include <qelapsedtimer.h>
452 #include <qscopedvaluerollback.h>
455 #include <QtNetwork/qsslsocket.h>
458 #include <private/qthread_p.h>
460 #ifdef QABSTRACTSOCKET_DEBUG
466 #define Q_CHECK_SOCKETENGINE(returnValue) do { \
467 if (!d->socketEngine) { \
468 return returnValue; \
471 #ifndef QABSTRACTSOCKET_BUFFERSIZE
472 #define QABSTRACTSOCKET_BUFFERSIZE 32768
474 #define QT_CONNECT_TIMEOUT 30000
475 #define QT_TRANSFER_TIMEOUT 120000
479 #if defined QABSTRACTSOCKET_DEBUG
480 QT_BEGIN_INCLUDE_NAMESPACE
483 QT_END_INCLUDE_NAMESPACE
486 Returns a human readable representation of the first \a len
487 characters in \a data.
489 static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
491 if (!data) return "(null)";
493 for (int i = 0; i < len; ++i) {
495 if (isprint(int(uchar(c)))) {
498 case '\n': out += "\\n"; break;
499 case '\r': out += "\\r"; break;
500 case '\t': out += "\\t"; break;
503 tmp.sprintf("\\%o", c);
504 out += tmp.toLatin1();
515 static bool isProxyError(QAbstractSocket::SocketError error)
518 case QAbstractSocket::ProxyAuthenticationRequiredError:
519 case QAbstractSocket::ProxyConnectionRefusedError:
520 case QAbstractSocket::ProxyConnectionClosedError:
521 case QAbstractSocket::ProxyConnectionTimeoutError:
522 case QAbstractSocket::ProxyNotFoundError:
523 case QAbstractSocket::ProxyProtocolError:
532 Constructs a QAbstractSocketPrivate. Initializes all members.
534 QAbstractSocketPrivate::QAbstractSocketPrivate()
535 : readSocketNotifierCalled(false),
536 readSocketNotifierState(false),
537 readSocketNotifierStateSet(false),
538 emittedReadyRead(false),
539 emittedBytesWritten(false),
543 pauseMode(QAbstractSocket::PauseNever),
548 cachedSocketDescriptor(-1),
549 readBufferMaxSize(0),
550 writeBuffer(QABSTRACTSOCKET_BUFFERSIZE),
552 blockingTimeout(30000),
555 connectTimeElapsed(0),
557 socketType(QAbstractSocket::UnknownSocketType),
558 state(QAbstractSocket::UnconnectedState),
559 socketError(QAbstractSocket::UnknownSocketError),
560 preferredNetworkLayerProtocol(QAbstractSocket::UnknownNetworkLayerProtocol)
566 Destructs the QAbstractSocket. If the socket layer is open, it
569 QAbstractSocketPrivate::~QAbstractSocketPrivate()
575 Resets the socket layer, clears the read and write buffers and
576 deletes any socket notifiers.
578 void QAbstractSocketPrivate::resetSocketLayer()
580 #if defined (QABSTRACTSOCKET_DEBUG)
581 qDebug("QAbstractSocketPrivate::resetSocketLayer()");
585 socketEngine->close();
586 socketEngine->disconnect();
589 cachedSocketDescriptor = -1;
592 connectTimer->stop();
594 disconnectTimer->stop();
599 Initializes the socket layer to by of type \a type, using the
600 network layer protocol \a protocol. Resets the socket layer first
601 if it's already initialized. Sets up the socket notifiers.
603 bool QAbstractSocketPrivate::initSocketLayer(QAbstractSocket::NetworkLayerProtocol protocol)
605 #ifdef QT_NO_NETWORKPROXY
606 // this is here to avoid a duplication of the call to createSocketEngine below
607 static const QNetworkProxy &proxyInUse = *(QNetworkProxy *)0;
610 Q_Q(QAbstractSocket);
611 #if defined (QABSTRACTSOCKET_DEBUG)
613 if (q->socketType() == QAbstractSocket::TcpSocket) typeStr = QLatin1String("TcpSocket");
614 else if (q->socketType() == QAbstractSocket::UdpSocket) typeStr = QLatin1String("UdpSocket");
615 else typeStr = QLatin1String("UnknownSocketType");
617 if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = QLatin1String("IPv4Protocol");
618 else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = QLatin1String("IPv6Protocol");
619 else protocolStr = QLatin1String("UnknownNetworkLayerProtocol");
623 socketEngine = QAbstractSocketEngine::createSocketEngine(q->socketType(), proxyInUse, q);
625 socketError = QAbstractSocket::UnsupportedSocketOperationError;
626 q->setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
629 #ifndef QT_NO_BEARERMANAGEMENT
630 //copy network session down to the socket engine (if it has been set)
631 socketEngine->setProperty("_q_networksession", q->property("_q_networksession"));
633 if (!socketEngine->initialize(q->socketType(), protocol)) {
634 #if defined (QABSTRACTSOCKET_DEBUG)
635 qDebug("QAbstractSocketPrivate::initSocketLayer(%s, %s) failed (%s)",
636 typeStr.toLatin1().constData(), protocolStr.toLatin1().constData(),
637 socketEngine->errorString().toLatin1().constData());
639 socketError = socketEngine->error();
640 q->setErrorString(socketEngine->errorString());
644 if (threadData->eventDispatcher)
645 socketEngine->setReceiver(this);
647 #if defined (QABSTRACTSOCKET_DEBUG)
648 qDebug("QAbstractSocketPrivate::initSocketLayer(%s, %s) success",
649 typeStr.toLatin1().constData(), protocolStr.toLatin1().constData());
656 Slot connected to the read socket notifier. This slot is called
657 when new data is available for reading, or when the socket has
658 been closed. Handles recursive calls.
660 bool QAbstractSocketPrivate::canReadNotification()
662 Q_Q(QAbstractSocket);
663 #if defined (QABSTRACTSOCKET_DEBUG)
664 qDebug("QAbstractSocketPrivate::canReadNotification()");
667 // Prevent recursive calls
668 if (readSocketNotifierCalled) {
669 if (!readSocketNotifierStateSet) {
670 readSocketNotifierStateSet = true;
671 readSocketNotifierState = socketEngine->isReadNotificationEnabled();
672 socketEngine->setReadNotificationEnabled(false);
675 QScopedValueRollback<bool> rsncrollback(readSocketNotifierCalled);
676 readSocketNotifierCalled = true;
679 socketEngine->setReadNotificationEnabled(false);
681 // If buffered, read data from the socket into the read buffer
684 // Return if there is no space in the buffer
685 if (readBufferMaxSize && buffer.size() >= readBufferMaxSize) {
686 #if defined (QABSTRACTSOCKET_DEBUG)
687 qDebug("QAbstractSocketPrivate::canReadNotification() buffer is full");
692 // If reading from the socket fails after getting a read
693 // notification, close the socket.
694 newBytes = buffer.size();
695 if (!readFromSocket()) {
696 #if defined (QABSTRACTSOCKET_DEBUG)
697 qDebug("QAbstractSocketPrivate::canReadNotification() disconnecting socket");
699 q->disconnectFromHost();
702 newBytes = buffer.size() - newBytes;
704 // If read buffer is full, disable the read socket notifier.
705 if (readBufferMaxSize && buffer.size() == readBufferMaxSize) {
706 socketEngine->setReadNotificationEnabled(false);
710 // only emit readyRead() when not recursing, and only if there is data available
711 bool hasData = newBytes > 0
712 #ifndef QT_NO_UDPSOCKET
713 || (!isBuffered && socketType != QAbstractSocket::TcpSocket && socketEngine && socketEngine->hasPendingDatagrams())
715 || (!isBuffered && socketType == QAbstractSocket::TcpSocket && socketEngine)
718 if (!emittedReadyRead && hasData) {
719 QScopedValueRollback<bool> r(emittedReadyRead);
720 emittedReadyRead = true;
724 // If we were closed as a result of the readyRead() signal,
726 if (state == QAbstractSocket::UnconnectedState || state == QAbstractSocket::ClosingState) {
727 #if defined (QABSTRACTSOCKET_DEBUG)
728 qDebug("QAbstractSocketPrivate::canReadNotification() socket is closing - returning");
733 if (!hasData && socketEngine)
734 socketEngine->setReadNotificationEnabled(true);
736 // reset the read socket notifier state if we reentered inside the
737 // readyRead() connected slot.
738 if (readSocketNotifierStateSet && socketEngine &&
739 readSocketNotifierState != socketEngine->isReadNotificationEnabled()) {
740 socketEngine->setReadNotificationEnabled(readSocketNotifierState);
741 readSocketNotifierStateSet = false;
748 Slot connected to the close socket notifier. It's called when the
751 void QAbstractSocketPrivate::canCloseNotification()
753 Q_Q(QAbstractSocket);
755 #if defined (QABSTRACTSOCKET_DEBUG)
756 qDebug("QAbstractSocketPrivate::canCloseNotification()");
761 // Try to read to the buffer, if the read fail we can close the socket.
762 newBytes = buffer.size();
763 if (!readFromSocket()) {
764 q->disconnectFromHost();
767 newBytes = buffer.size() - newBytes;
769 // If there was still some data to be read from the socket
770 // then we could get another FD_READ. The disconnect will
771 // then occur when we read from the socket again and fail
772 // in canReadNotification or by the manually created
773 // closeNotification below.
776 QMetaObject::invokeMethod(socketEngine, "closeNotification", Qt::QueuedConnection);
778 } else if (socketType == QAbstractSocket::TcpSocket && socketEngine) {
786 Slot connected to the write socket notifier. It's called during a
787 delayed connect or when the socket is ready for writing.
789 bool QAbstractSocketPrivate::canWriteNotification()
791 #if defined (Q_OS_WIN)
792 if (socketEngine && socketEngine->isWriteNotificationEnabled())
793 socketEngine->setWriteNotificationEnabled(false);
796 #if defined (QABSTRACTSOCKET_DEBUG)
797 qDebug("QAbstractSocketPrivate::canWriteNotification() flushing");
799 int tmp = writeBuffer.size();
803 #if defined (Q_OS_WIN)
804 if (!writeBuffer.isEmpty())
805 socketEngine->setWriteNotificationEnabled(true);
807 if (writeBuffer.isEmpty() && socketEngine->bytesToWrite() == 0)
808 socketEngine->setWriteNotificationEnabled(false);
812 return (writeBuffer.size() < tmp);
817 Slot connected to a notification of connection status
818 change. Either we finished connecting or we failed to connect.
820 void QAbstractSocketPrivate::connectionNotification()
822 // If in connecting state, check if the connection has been
823 // established, otherwise flush pending data.
824 if (state == QAbstractSocket::ConnectingState) {
825 #if defined (QABSTRACTSOCKET_DEBUG)
826 qDebug("QAbstractSocketPrivate::connectionNotification() testing connection");
834 Writes pending data in the write buffers to the socket. The
835 function writes as much as it can without blocking.
837 It is usually invoked by canWriteNotification after one or more
840 Emits bytesWritten().
842 bool QAbstractSocketPrivate::flush()
844 Q_Q(QAbstractSocket);
845 if (!socketEngine || !socketEngine->isValid() || (writeBuffer.isEmpty()
846 && socketEngine->bytesToWrite() == 0)) {
847 #if defined (QABSTRACTSOCKET_DEBUG)
848 qDebug("QAbstractSocketPrivate::flush() nothing to do: valid ? %s, writeBuffer.isEmpty() ? %s",
849 (socketEngine && socketEngine->isValid()) ? "yes" : "no", writeBuffer.isEmpty() ? "yes" : "no");
852 // this covers the case when the buffer was empty, but we had to wait for the socket engine to finish
853 if (state == QAbstractSocket::ClosingState)
854 q->disconnectFromHost();
859 int nextSize = writeBuffer.nextDataBlockSize();
860 const char *ptr = writeBuffer.readPointer();
862 // Attempt to write it all in one chunk.
863 qint64 written = socketEngine->write(ptr, nextSize);
865 socketError = socketEngine->error();
866 q->setErrorString(socketEngine->errorString());
867 #if defined (QABSTRACTSOCKET_DEBUG)
868 qDebug() << "QAbstractSocketPrivate::flush() write error, aborting." << socketEngine->errorString();
870 emit q->error(socketError);
871 // an unexpected error so close the socket.
876 #if defined (QABSTRACTSOCKET_DEBUG)
877 qDebug("QAbstractSocketPrivate::flush() %lld bytes written to the network",
881 // Remove what we wrote so far.
882 writeBuffer.free(written);
884 // Don't emit bytesWritten() recursively.
885 if (!emittedBytesWritten) {
886 QScopedValueRollback<bool> r(emittedBytesWritten);
887 emittedBytesWritten = true;
888 emit q->bytesWritten(written);
892 if (writeBuffer.isEmpty() && socketEngine && socketEngine->isWriteNotificationEnabled()
893 && !socketEngine->bytesToWrite())
894 socketEngine->setWriteNotificationEnabled(false);
895 if (state == QAbstractSocket::ClosingState)
896 q->disconnectFromHost();
901 #ifndef QT_NO_NETWORKPROXY
904 Resolve the proxy to its final value.
906 void QAbstractSocketPrivate::resolveProxy(const QString &hostname, quint16 port)
908 QList<QNetworkProxy> proxies;
910 if (proxy.type() != QNetworkProxy::DefaultProxy) {
911 // a non-default proxy was set with setProxy
914 // try the application settings instead
915 QNetworkProxyQuery query(hostname, port, QString(),
916 socketType == QAbstractSocket::TcpSocket ?
917 QNetworkProxyQuery::TcpSocket :
918 QNetworkProxyQuery::UdpSocket);
919 proxies = QNetworkProxyFactory::proxyForQuery(query);
922 // return the first that we can use
923 foreach (const QNetworkProxy &p, proxies) {
924 if (socketType == QAbstractSocket::UdpSocket &&
925 (p.capabilities() & QNetworkProxy::UdpTunnelingCapability) == 0)
928 if (socketType == QAbstractSocket::TcpSocket &&
929 (p.capabilities() & QNetworkProxy::TunnelingCapability) == 0)
937 // DefaultProxy here will raise an error
938 proxyInUse = QNetworkProxy();
944 Starts the connection to \a host, like _q_startConnecting below,
945 but without hostname resolution.
947 void QAbstractSocketPrivate::startConnectingByName(const QString &host)
949 Q_Q(QAbstractSocket);
950 if (state == QAbstractSocket::ConnectingState || state == QAbstractSocket::ConnectedState)
953 #if defined(QABSTRACTSOCKET_DEBUG)
954 qDebug("QAbstractSocketPrivate::startConnectingByName(host == %s)", qPrintable(host));
957 // ### Let the socket engine drive this?
958 state = QAbstractSocket::ConnectingState;
959 emit q->stateChanged(state);
961 connectTimeElapsed = 0;
963 if (initSocketLayer(QAbstractSocket::UnknownNetworkLayerProtocol)) {
964 if (socketEngine->connectToHostByName(host, port) ||
965 socketEngine->state() == QAbstractSocket::ConnectingState) {
966 cachedSocketDescriptor = socketEngine->socketDescriptor();
972 socketError = socketEngine->error();
973 q->setErrorString(socketEngine->errorString());
976 state = QAbstractSocket::UnconnectedState;
977 emit q->error(socketError);
978 emit q->stateChanged(state);
985 Slot connected to QHostInfo::lookupHost() in connectToHost(). This
986 function starts the process of connecting to any number of
987 candidate IP addresses for the host, if it was found. Calls
988 _q_connectToNextAddress().
990 void QAbstractSocketPrivate::_q_startConnecting(const QHostInfo &hostInfo)
992 Q_Q(QAbstractSocket);
994 if (state != QAbstractSocket::HostLookupState)
997 if (hostLookupId != -1 && hostLookupId != hostInfo.lookupId()) {
998 qWarning("QAbstractSocketPrivate::_q_startConnecting() received hostInfo for wrong lookup ID %d expected %d", hostInfo.lookupId(), hostLookupId);
1001 // Only add the addresses for the preferred network layer.
1002 // Or all if preferred network layer is not set.
1003 if (preferredNetworkLayerProtocol == QAbstractSocket::UnknownNetworkLayerProtocol || preferredNetworkLayerProtocol == QAbstractSocket::AnyIPProtocol) {
1004 addresses = hostInfo.addresses();
1006 foreach (const QHostAddress &address, hostInfo.addresses())
1007 if (address.protocol() == preferredNetworkLayerProtocol)
1008 addresses += address;
1012 #if defined(QABSTRACTSOCKET_DEBUG)
1013 QString s = QLatin1String("{");
1014 for (int i = 0; i < addresses.count(); ++i) {
1015 if (i != 0) s += QLatin1String(", ");
1016 s += addresses.at(i).toString();
1018 s += QLatin1Char('}');
1019 qDebug("QAbstractSocketPrivate::_q_startConnecting(hostInfo == %s)", s.toLatin1().constData());
1022 // Try all addresses twice.
1023 addresses += addresses;
1025 // If there are no addresses in the host list, report this to the
1027 if (addresses.isEmpty()) {
1028 #if defined(QABSTRACTSOCKET_DEBUG)
1029 qDebug("QAbstractSocketPrivate::_q_startConnecting(), host not found");
1031 state = QAbstractSocket::UnconnectedState;
1032 socketError = QAbstractSocket::HostNotFoundError;
1033 q->setErrorString(QAbstractSocket::tr("Host not found"));
1034 emit q->stateChanged(state);
1035 emit q->error(QAbstractSocket::HostNotFoundError);
1039 // Enter Connecting state (see also sn_write, which is called by
1040 // the write socket notifier after connect())
1041 state = QAbstractSocket::ConnectingState;
1042 emit q->stateChanged(state);
1044 // Report the successful host lookup
1045 emit q->hostFound();
1047 // Reset the total time spent connecting.
1048 connectTimeElapsed = 0;
1050 // The addresses returned by the lookup will be tested one after
1051 // another by _q_connectToNextAddress().
1052 _q_connectToNextAddress();
1057 Called by a queued or direct connection from _q_startConnecting() or
1058 _q_testConnection(), this function takes the first address of the
1059 pending addresses list and tries to connect to it. If the
1060 connection succeeds, QAbstractSocket will emit
1061 connected(). Otherwise, error(ConnectionRefusedError) or
1062 error(SocketTimeoutError) is emitted.
1064 void QAbstractSocketPrivate::_q_connectToNextAddress()
1066 Q_Q(QAbstractSocket);
1068 // Check for more pending addresses
1069 if (addresses.isEmpty()) {
1070 #if defined(QABSTRACTSOCKET_DEBUG)
1071 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), all addresses failed.");
1073 state = QAbstractSocket::UnconnectedState;
1075 if ((socketEngine->error() == QAbstractSocket::UnknownSocketError
1077 // On AIX, the second connect call will result in EINVAL and not
1078 // ECONNECTIONREFUSED; although the meaning is the same.
1079 || socketEngine->error() == QAbstractSocket::UnsupportedSocketOperationError
1081 ) && socketEngine->state() == QAbstractSocket::ConnectingState) {
1082 socketError = QAbstractSocket::ConnectionRefusedError;
1083 q->setErrorString(QAbstractSocket::tr("Connection refused"));
1085 socketError = socketEngine->error();
1086 q->setErrorString(socketEngine->errorString());
1089 // socketError = QAbstractSocket::ConnectionRefusedError;
1090 // q->setErrorString(QAbstractSocket::tr("Connection refused"));
1092 emit q->stateChanged(state);
1093 emit q->error(socketError);
1097 // Pick the first host address candidate
1098 host = addresses.takeFirst();
1099 #if defined(QABSTRACTSOCKET_DEBUG)
1100 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), connecting to %s:%i, %d left to try",
1101 host.toString().toLatin1().constData(), port, addresses.count());
1104 if (!initSocketLayer(host.protocol())) {
1105 // hope that the next address is better
1106 #if defined(QABSTRACTSOCKET_DEBUG)
1107 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), failed to initialize sock layer");
1112 // Tries to connect to the address. If it succeeds immediately
1113 // (localhost address on BSD or any UDP connect), emit
1114 // connected() and return.
1115 if (socketEngine->connectToHost(host, port)) {
1116 //_q_testConnection();
1117 fetchConnectionParameters();
1121 // cache the socket descriptor even if we're not fully connected yet
1122 cachedSocketDescriptor = socketEngine->socketDescriptor();
1124 // Check that we're in delayed connection state. If not, try
1126 if (socketEngine->state() != QAbstractSocket::ConnectingState) {
1127 #if defined(QABSTRACTSOCKET_DEBUG)
1128 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), connection failed (%s)",
1129 socketEngine->errorString().toLatin1().constData());
1134 // Start the connect timer.
1135 if (threadData->eventDispatcher) {
1136 if (!connectTimer) {
1137 connectTimer = new QTimer(q);
1138 QObject::connect(connectTimer, SIGNAL(timeout()),
1139 q, SLOT(_q_abortConnectionAttempt()),
1140 Qt::DirectConnection);
1142 connectTimer->start(QT_CONNECT_TIMEOUT);
1145 // Wait for a write notification that will eventually call
1146 // _q_testConnection().
1147 socketEngine->setWriteNotificationEnabled(true);
1149 } while (state != QAbstractSocket::ConnectedState);
1154 Tests if a connection has been established. If it has, connected()
1155 is emitted. Otherwise, _q_connectToNextAddress() is invoked.
1157 void QAbstractSocketPrivate::_q_testConnection()
1160 if (threadData->eventDispatcher) {
1162 connectTimer->stop();
1165 if (socketEngine->state() == QAbstractSocket::ConnectedState) {
1166 // Fetch the parameters if our connection is completed;
1167 // otherwise, fall out and try the next address.
1168 fetchConnectionParameters();
1170 q_func()->disconnectFromHost();
1171 pendingClose = false;
1176 // don't retry the other addresses if we had a proxy error
1177 if (isProxyError(socketEngine->error()))
1181 if (threadData->eventDispatcher) {
1183 connectTimer->stop();
1186 #if defined(QABSTRACTSOCKET_DEBUG)
1187 qDebug("QAbstractSocketPrivate::_q_testConnection() connection failed,"
1188 " checking for alternative addresses");
1190 _q_connectToNextAddress();
1195 This function is called after a certain number of seconds has
1196 passed while waiting for a connection. It simply tests the
1197 connection, and continues to the next address if the connection
1200 void QAbstractSocketPrivate::_q_abortConnectionAttempt()
1202 Q_Q(QAbstractSocket);
1203 #if defined(QABSTRACTSOCKET_DEBUG)
1204 qDebug("QAbstractSocketPrivate::_q_abortConnectionAttempt() (timed out)");
1207 socketEngine->setWriteNotificationEnabled(false);
1209 connectTimer->stop();
1211 if (addresses.isEmpty()) {
1212 state = QAbstractSocket::UnconnectedState;
1213 socketError = QAbstractSocket::SocketTimeoutError;
1214 q->setErrorString(QAbstractSocket::tr("Connection timed out"));
1215 emit q->stateChanged(state);
1216 emit q->error(socketError);
1218 _q_connectToNextAddress();
1222 void QAbstractSocketPrivate::_q_forceDisconnect()
1224 Q_Q(QAbstractSocket);
1225 if (socketEngine && socketEngine->isValid() && state == QAbstractSocket::ClosingState) {
1226 socketEngine->close();
1227 q->disconnectFromHost();
1233 Reads data from the socket layer into the read buffer. Returns
1234 true on success; otherwise false.
1236 bool QAbstractSocketPrivate::readFromSocket()
1238 Q_Q(QAbstractSocket);
1239 // Find how many bytes we can read from the socket layer.
1240 qint64 bytesToRead = socketEngine->bytesAvailable();
1241 if (bytesToRead == 0) {
1242 // Under heavy load, certain conditions can trigger read notifications
1243 // for socket notifiers on which there is no activity. If we continue
1244 // to read 0 bytes from the socket, we will trigger behavior similar
1245 // to that which signals a remote close. When we hit this condition,
1246 // we try to read 4k of data from the socket, which will give us either
1247 // an EAGAIN/EWOULDBLOCK if the connection is alive (i.e., the remote
1248 // host has _not_ disappeared).
1251 if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - buffer.size()))
1252 bytesToRead = readBufferMaxSize - buffer.size();
1254 #if defined(QABSTRACTSOCKET_DEBUG)
1255 qDebug("QAbstractSocketPrivate::readFromSocket() about to read %d bytes",
1259 // Read from the socket, store data in the read buffer.
1260 char *ptr = buffer.reserve(bytesToRead);
1261 qint64 readBytes = socketEngine->read(ptr, bytesToRead);
1262 if (readBytes == -2) {
1263 // No bytes currently available for reading.
1264 buffer.chop(bytesToRead);
1267 buffer.chop(int(bytesToRead - (readBytes < 0 ? qint64(0) : readBytes)));
1268 #if defined(QABSTRACTSOCKET_DEBUG)
1269 qDebug("QAbstractSocketPrivate::readFromSocket() got %d bytes, buffer size = %d",
1270 int(readBytes), buffer.size());
1273 if (!socketEngine->isValid()) {
1274 socketError = socketEngine->error();
1275 q->setErrorString(socketEngine->errorString());
1276 emit q->error(socketError);
1277 #if defined(QABSTRACTSOCKET_DEBUG)
1278 qDebug("QAbstractSocketPrivate::readFromSocket() read failed: %s",
1279 q->errorString().toLatin1().constData());
1290 Sets up the internal state after the connection has succeeded.
1292 void QAbstractSocketPrivate::fetchConnectionParameters()
1294 Q_Q(QAbstractSocket);
1296 peerName = hostName;
1298 socketEngine->setReadNotificationEnabled(true);
1299 socketEngine->setWriteNotificationEnabled(true);
1300 localPort = socketEngine->localPort();
1301 peerPort = socketEngine->peerPort();
1302 localAddress = socketEngine->localAddress();
1303 peerAddress = socketEngine->peerAddress();
1304 cachedSocketDescriptor = socketEngine->socketDescriptor();
1307 state = QAbstractSocket::ConnectedState;
1308 emit q->stateChanged(state);
1309 emit q->connected();
1311 #if defined(QABSTRACTSOCKET_DEBUG)
1312 qDebug("QAbstractSocketPrivate::fetchConnectionParameters() connection to %s:%i established",
1313 host.toString().toLatin1().constData(), port);
1318 void QAbstractSocketPrivate::pauseSocketNotifiers(QAbstractSocket *socket)
1320 QAbstractSocketEngine *socketEngine = socket->d_func()->socketEngine;
1323 socket->d_func()->prePauseReadSocketNotifierState = socketEngine->isReadNotificationEnabled();
1324 socket->d_func()->prePauseWriteSocketNotifierState = socketEngine->isWriteNotificationEnabled();
1325 socket->d_func()->prePauseExceptionSocketNotifierState = socketEngine->isExceptionNotificationEnabled();
1326 socketEngine->setReadNotificationEnabled(false);
1327 socketEngine->setWriteNotificationEnabled(false);
1328 socketEngine->setExceptionNotificationEnabled(false);
1331 void QAbstractSocketPrivate::resumeSocketNotifiers(QAbstractSocket *socket)
1333 QAbstractSocketEngine *socketEngine = socket->d_func()->socketEngine;
1336 socketEngine->setReadNotificationEnabled(socket->d_func()->prePauseReadSocketNotifierState);
1337 socketEngine->setWriteNotificationEnabled(socket->d_func()->prePauseWriteSocketNotifierState);
1338 socketEngine->setExceptionNotificationEnabled(socket->d_func()->prePauseExceptionSocketNotifierState);
1341 QAbstractSocketEngine* QAbstractSocketPrivate::getSocketEngine(QAbstractSocket *socket)
1343 return socket->d_func()->socketEngine;
1349 Constructs a new abstract socket of type \a socketType. The \a
1350 parent argument is passed to QObject's constructor.
1352 QAbstractSocket::QAbstractSocket(SocketType socketType,
1353 QAbstractSocketPrivate &dd, QObject *parent)
1354 : QIODevice(dd, parent)
1356 Q_D(QAbstractSocket);
1357 #if defined(QABSTRACTSOCKET_DEBUG)
1358 qDebug("QAbstractSocket::QAbstractSocket(%sSocket, QAbstractSocketPrivate == %p, parent == %p)",
1359 socketType == TcpSocket ? "Tcp" : socketType == UdpSocket
1360 ? "Udp" : "Unknown", &dd, parent);
1362 d->socketType = socketType;
1366 Creates a new abstract socket of type \a socketType. The \a
1367 parent argument is passed to QObject's constructor.
1369 \sa socketType(), QTcpSocket, QUdpSocket
1371 QAbstractSocket::QAbstractSocket(SocketType socketType, QObject *parent)
1372 : QIODevice(*new QAbstractSocketPrivate, parent)
1374 Q_D(QAbstractSocket);
1375 #if defined(QABSTRACTSOCKET_DEBUG)
1376 qDebug("QAbstractSocket::QAbstractSocket(%p)", parent);
1378 d->socketType = socketType;
1382 Destroys the socket.
1384 QAbstractSocket::~QAbstractSocket()
1386 Q_D(QAbstractSocket);
1387 #if defined(QABSTRACTSOCKET_DEBUG)
1388 qDebug("QAbstractSocket::~QAbstractSocket()");
1390 if (d->state != UnconnectedState)
1397 Continues data transfer on the socket. This method should only be used
1398 after the socket has been set to pause upon notifications and a
1399 notification has been received.
1400 The only notification currently supported is QSslSocket::sslErrors().
1401 Calling this method if the socket is not paused results in undefined
1404 \sa pauseMode(), setPauseMode()
1406 void QAbstractSocket::resume()
1408 QAbstractSocketPrivate::resumeSocketNotifiers(this);
1414 Returns the pause mode of this socket.
1416 \sa setPauseMode(), resume()
1418 QAbstractSocket::PauseModes QAbstractSocket::pauseMode() const
1420 return d_func()->pauseMode;
1427 Controls whether to pause upon receiving a notification. The \a pauseMode parameter
1428 specifies the conditions in which the socket should be paused. The only notification
1429 currently supported is QSslSocket::sslErrors(). If set to PauseOnSslErrors,
1430 data transfer on the socket will be paused and needs to be enabled explicitly
1431 again by calling resume().
1432 By default this option is set to PauseNever.
1433 This option must be called before connecting to the server, otherwise it will
1434 result in undefined behavior.
1436 \sa pauseMode(), resume()
1438 void QAbstractSocket::setPauseMode(PauseModes pauseMode)
1440 d_func()->pauseMode = pauseMode;
1446 Binds to \a address on port \a port, using the BindMode \a mode.
1448 Binds this socket to the address \a address and the port \a port.
1450 For UDP sockets, after binding, the signal QUdpSocket::readyRead() is emitted
1451 whenever a UDP datagram arrives on the specified address and port.
1452 Thus, This function is useful to write UDP servers.
1454 For TCP sockets, this function may be used to specify which interface to use
1455 for an outgoing connection, which is useful in case of multiple network
1458 By default, the socket is bound using the DefaultForPlatform BindMode.
1459 If a port is not specified, a random port is chosen.
1461 On success, the functions returns true and the socket enters
1462 BoundState; otherwise it returns false.
1465 bool QAbstractSocket::bind(const QHostAddress &address, quint16 port, BindMode mode)
1467 Q_D(QAbstractSocket);
1469 // now check if the socket engine is initialized and to the right type
1470 if (!d->socketEngine || !d->socketEngine->isValid()) {
1471 QHostAddress nullAddress;
1472 d->resolveProxy(nullAddress.toString(), port);
1474 QAbstractSocket::NetworkLayerProtocol protocol = address.protocol();
1475 if (protocol == QAbstractSocket::UnknownNetworkLayerProtocol)
1476 protocol = nullAddress.protocol();
1478 if (!d->initSocketLayer(protocol))
1482 if (mode != DefaultForPlatform) {
1484 if ((mode & ShareAddress) || (mode & ReuseAddressHint))
1485 d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
1487 d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 0);
1490 if (mode & ReuseAddressHint)
1491 d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
1493 d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 0);
1494 if (mode & DontShareAddress)
1495 d->socketEngine->setOption(QAbstractSocketEngine::BindExclusively, 1);
1497 d->socketEngine->setOption(QAbstractSocketEngine::BindExclusively, 0);
1500 bool result = d->socketEngine->bind(address, port);
1501 d->cachedSocketDescriptor = d->socketEngine->socketDescriptor();
1504 d->socketError = d->socketEngine->error();
1505 setErrorString(d->socketEngine->errorString());
1506 emit error(d->socketError);
1510 d->state = BoundState;
1511 d->localAddress = d->socketEngine->localAddress();
1512 d->localPort = d->socketEngine->localPort();
1514 emit stateChanged(d->state);
1515 d->socketEngine->setReadNotificationEnabled(true);
1523 Binds to QHostAddress:Any on port \a port, using the BindMode \a mode.
1525 By default, the socket is bound using the DefaultForPlatform BindMode.
1526 If a port is not specified, a random port is chosen.
1528 bool QAbstractSocket::bind(quint16 port, BindMode mode)
1530 return bind(QHostAddress::Any, port, mode);
1534 Returns true if the socket is valid and ready for use; otherwise
1537 \b{Note:} The socket's state must be ConnectedState before reading and
1542 bool QAbstractSocket::isValid() const
1544 return d_func()->socketEngine ? d_func()->socketEngine->isValid() : isOpen();
1548 Attempts to make a connection to \a hostName on the given \a port.
1549 The \a protocol parameter can be used to specify which network
1550 protocol to use (eg. IPv4 or IPv6).
1552 The socket is opened in the given \a openMode and first enters
1553 HostLookupState, then performs a host name lookup of \a hostName.
1554 If the lookup succeeds, hostFound() is emitted and QAbstractSocket
1555 enters ConnectingState. It then attempts to connect to the address
1556 or addresses returned by the lookup. Finally, if a connection is
1557 established, QAbstractSocket enters ConnectedState and
1560 At any point, the socket can emit error() to signal that an error
1563 \a hostName may be an IP address in string form (e.g.,
1564 "43.195.83.32"), or it may be a host name (e.g.,
1565 "example.com"). QAbstractSocket will do a lookup only if
1566 required. \a port is in native byte order.
1568 \sa state(), peerName(), peerAddress(), peerPort(), waitForConnected()
1570 void QAbstractSocket::connectToHost(const QString &hostName, quint16 port,
1572 NetworkLayerProtocol protocol)
1574 Q_D(QAbstractSocket);
1575 #if defined(QABSTRACTSOCKET_DEBUG)
1576 qDebug("QAbstractSocket::connectToHost(\"%s\", %i, %i)...", qPrintable(hostName), port,
1580 if (d->state == ConnectedState || d->state == ConnectingState
1581 || d->state == ClosingState || d->state == HostLookupState) {
1582 qWarning("QAbstractSocket::connectToHost() called when already looking up or connecting/connected to \"%s\"", qPrintable(hostName));
1583 d->socketError = QAbstractSocket::OperationError;
1584 setErrorString(QAbstractSocket::tr("Trying to connect while connection is in progress"));
1585 emit error(d->socketError);
1589 d->preferredNetworkLayerProtocol = protocol;
1590 d->hostName = hostName;
1592 d->state = UnconnectedState;
1594 d->writeBuffer.clear();
1595 d->abortCalled = false;
1596 d->closeCalled = false;
1597 d->pendingClose = false;
1600 d->localAddress.clear();
1601 d->peerAddress.clear();
1602 d->peerName = hostName;
1603 if (d->hostLookupId != -1) {
1604 QHostInfo::abortHostLookup(d->hostLookupId);
1605 d->hostLookupId = -1;
1608 #ifndef QT_NO_NETWORKPROXY
1609 // Get the proxy information
1610 d->resolveProxy(hostName, port);
1611 if (d->proxyInUse.type() == QNetworkProxy::DefaultProxy) {
1612 // failed to setup the proxy
1613 d->socketError = QAbstractSocket::UnsupportedSocketOperationError;
1614 setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
1615 emit error(d->socketError);
1620 if (openMode & QIODevice::Unbuffered)
1621 d->isBuffered = false; // Unbuffered QTcpSocket
1622 else if (!d_func()->isBuffered)
1623 openMode |= QAbstractSocket::Unbuffered; // QUdpSocket
1625 QIODevice::open(openMode);
1626 d->state = HostLookupState;
1627 emit stateChanged(d->state);
1630 if (temp.setAddress(hostName)) {
1632 info.setAddresses(QList<QHostAddress>() << temp);
1633 d->_q_startConnecting(info);
1634 #ifndef QT_NO_NETWORKPROXY
1635 } else if (d->proxyInUse.capabilities() & QNetworkProxy::HostNameLookupCapability) {
1636 // the proxy supports connection by name, so use it
1637 d->startConnectingByName(hostName);
1641 if (d->threadData->eventDispatcher) {
1642 // this internal API for QHostInfo either immediately gives us the desired
1643 // QHostInfo from cache or later calls the _q_startConnecting slot.
1644 bool immediateResultValid = false;
1645 QHostInfo hostInfo = qt_qhostinfo_lookup(hostName,
1647 SLOT(_q_startConnecting(QHostInfo)),
1648 &immediateResultValid,
1650 if (immediateResultValid) {
1651 d->hostLookupId = -1;
1652 d->_q_startConnecting(hostInfo);
1657 #if defined(QABSTRACTSOCKET_DEBUG)
1658 qDebug("QAbstractSocket::connectToHost(\"%s\", %i) == %s%s", hostName.toLatin1().constData(), port,
1659 (d->state == ConnectedState) ? "true" : "false",
1660 (d->state == ConnectingState || d->state == HostLookupState)
1661 ? " (connection in progress)" : "");
1667 Attempts to make a connection to \a address on port \a port.
1669 void QAbstractSocket::connectToHost(const QHostAddress &address, quint16 port,
1672 #if defined(QABSTRACTSOCKET_DEBUG)
1673 qDebug("QAbstractSocket::connectToHost([%s], %i, %i)...",
1674 address.toString().toLatin1().constData(), port, (int) openMode);
1676 connectToHost(address.toString(), port, openMode);
1680 Returns the number of bytes that are waiting to be written. The
1681 bytes are written when control goes back to the event loop or
1682 when flush() is called.
1684 \sa bytesAvailable(), flush()
1686 qint64 QAbstractSocket::bytesToWrite() const
1688 Q_D(const QAbstractSocket);
1689 #if defined(QABSTRACTSOCKET_DEBUG)
1690 qDebug("QAbstractSocket::bytesToWrite() == %i", d->writeBuffer.size());
1692 return (qint64)d->writeBuffer.size();
1696 Returns the number of incoming bytes that are waiting to be read.
1698 \sa bytesToWrite(), read()
1700 qint64 QAbstractSocket::bytesAvailable() const
1702 Q_D(const QAbstractSocket);
1703 qint64 available = QIODevice::bytesAvailable();
1705 if (!d->isBuffered && d->socketEngine && d->socketEngine->isValid())
1706 available += d->socketEngine->bytesAvailable();
1708 #if defined(QABSTRACTSOCKET_DEBUG)
1709 qDebug("QAbstractSocket::bytesAvailable() == %llu", available);
1715 Returns the host port number (in native byte order) of the local
1716 socket if available; otherwise returns 0.
1718 \sa localAddress(), peerPort(), setLocalPort()
1720 quint16 QAbstractSocket::localPort() const
1722 Q_D(const QAbstractSocket);
1723 return d->localPort;
1727 Returns the host address of the local socket if available;
1728 otherwise returns QHostAddress::Null.
1730 This is normally the main IP address of the host, but can be
1731 QHostAddress::LocalHost (127.0.0.1) for connections to the
1734 \sa localPort(), peerAddress(), setLocalAddress()
1736 QHostAddress QAbstractSocket::localAddress() const
1738 Q_D(const QAbstractSocket);
1739 return d->localAddress;
1743 Returns the port of the connected peer if the socket is in
1744 ConnectedState; otherwise returns 0.
1746 \sa peerAddress(), localPort(), setPeerPort()
1748 quint16 QAbstractSocket::peerPort() const
1750 Q_D(const QAbstractSocket);
1755 Returns the address of the connected peer if the socket is in
1756 ConnectedState; otherwise returns QHostAddress::Null.
1758 \sa peerName(), peerPort(), localAddress(), setPeerAddress()
1760 QHostAddress QAbstractSocket::peerAddress() const
1762 Q_D(const QAbstractSocket);
1763 return d->peerAddress;
1767 Returns the name of the peer as specified by connectToHost(), or
1768 an empty QString if connectToHost() has not been called.
1770 \sa peerAddress(), peerPort(), setPeerName()
1772 QString QAbstractSocket::peerName() const
1774 Q_D(const QAbstractSocket);
1775 return d->peerName.isEmpty() ? d->hostName : d->peerName;
1779 Returns true if a line of data can be read from the socket;
1780 otherwise returns false.
1784 bool QAbstractSocket::canReadLine() const
1786 bool hasLine = d_func()->buffer.canReadLine();
1787 #if defined (QABSTRACTSOCKET_DEBUG)
1788 qDebug("QAbstractSocket::canReadLine() == %s, buffer size = %d, size = %d", hasLine ? "true" : "false",
1789 d_func()->buffer.size(), d_func()->buffer.size());
1791 return hasLine || QIODevice::canReadLine();
1795 Returns the native socket descriptor of the QAbstractSocket object
1796 if this is available; otherwise returns -1.
1798 If the socket is using QNetworkProxy, the returned descriptor
1799 may not be usable with native socket functions.
1801 The socket descriptor is not available when QAbstractSocket is in
1804 \sa setSocketDescriptor()
1806 qintptr QAbstractSocket::socketDescriptor() const
1808 Q_D(const QAbstractSocket);
1809 return d->cachedSocketDescriptor;
1813 Initializes QAbstractSocket with the native socket descriptor \a
1814 socketDescriptor. Returns true if \a socketDescriptor is accepted
1815 as a valid socket descriptor; otherwise returns false.
1816 The socket is opened in the mode specified by \a openMode, and
1817 enters the socket state specified by \a socketState.
1819 \b{Note:} It is not possible to initialize two abstract sockets
1820 with the same native socket descriptor.
1822 \sa socketDescriptor()
1824 bool QAbstractSocket::setSocketDescriptor(qintptr socketDescriptor, SocketState socketState,
1827 Q_D(QAbstractSocket);
1829 d->resetSocketLayer();
1830 d->socketEngine = QAbstractSocketEngine::createSocketEngine(socketDescriptor, this);
1831 if (!d->socketEngine) {
1832 d->socketError = UnsupportedSocketOperationError;
1833 setErrorString(tr("Operation on socket is not supported"));
1836 #ifndef QT_NO_BEARERMANAGEMENT
1837 //copy network session down to the socket engine (if it has been set)
1838 d->socketEngine->setProperty("_q_networksession", property("_q_networksession"));
1840 bool result = d->socketEngine->initialize(socketDescriptor, socketState);
1842 d->socketError = d->socketEngine->error();
1843 setErrorString(d->socketEngine->errorString());
1847 if (d->threadData->eventDispatcher)
1848 d->socketEngine->setReceiver(d);
1850 QIODevice::open(openMode);
1852 if (d->state != socketState) {
1853 d->state = socketState;
1854 emit stateChanged(d->state);
1857 d->pendingClose = false;
1858 d->socketEngine->setReadNotificationEnabled(true);
1859 d->localPort = d->socketEngine->localPort();
1860 d->peerPort = d->socketEngine->peerPort();
1861 d->localAddress = d->socketEngine->localAddress();
1862 d->peerAddress = d->socketEngine->peerAddress();
1863 d->cachedSocketDescriptor = socketDescriptor;
1870 Sets the given \a option to the value described by \a value.
1874 void QAbstractSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
1876 if (!d_func()->socketEngine)
1880 case LowDelayOption:
1881 d_func()->socketEngine->setOption(QAbstractSocketEngine::LowDelayOption, value.toInt());
1884 case KeepAliveOption:
1885 d_func()->socketEngine->setOption(QAbstractSocketEngine::KeepAliveOption, value.toInt());
1888 case MulticastTtlOption:
1889 d_func()->socketEngine->setOption(QAbstractSocketEngine::MulticastTtlOption, value.toInt());
1892 case MulticastLoopbackOption:
1893 d_func()->socketEngine->setOption(QAbstractSocketEngine::MulticastLoopbackOption, value.toInt());
1896 case TypeOfServiceOption:
1897 d_func()->socketEngine->setOption(QAbstractSocketEngine::TypeOfServiceOption, value.toInt());
1904 Returns the value of the \a option option.
1906 \sa setSocketOption()
1908 QVariant QAbstractSocket::socketOption(QAbstractSocket::SocketOption option)
1910 if (!d_func()->socketEngine)
1915 case LowDelayOption:
1916 ret = d_func()->socketEngine->option(QAbstractSocketEngine::LowDelayOption);
1919 case KeepAliveOption:
1920 ret = d_func()->socketEngine->option(QAbstractSocketEngine::KeepAliveOption);
1923 case MulticastTtlOption:
1924 ret = d_func()->socketEngine->option(QAbstractSocketEngine::MulticastTtlOption);
1926 case MulticastLoopbackOption:
1927 ret = d_func()->socketEngine->option(QAbstractSocketEngine::MulticastLoopbackOption);
1930 case TypeOfServiceOption:
1931 ret = d_func()->socketEngine->option(QAbstractSocketEngine::TypeOfServiceOption);
1937 return QVariant(ret);
1942 Returns the difference between msecs and elapsed. If msecs is -1,
1943 however, -1 is returned.
1945 static int qt_timeout_value(int msecs, int elapsed)
1950 int timeout = msecs - elapsed;
1951 return timeout < 0 ? 0 : timeout;
1955 Waits until the socket is connected, up to \a msecs
1956 milliseconds. If the connection has been established, this
1957 function returns true; otherwise it returns false. In the case
1958 where it returns false, you can call error() to determine
1959 the cause of the error.
1961 The following example waits up to one second for a connection
1964 \snippet code/src_network_socket_qabstractsocket.cpp 0
1966 If msecs is -1, this function will not time out.
1968 \note This function may wait slightly longer than \a msecs,
1969 depending on the time it takes to complete the host lookup.
1971 \note Multiple calls to this functions do not accumulate the time.
1972 If the function times out, the connecting process will be aborted.
1974 \sa connectToHost(), connected()
1976 bool QAbstractSocket::waitForConnected(int msecs)
1978 Q_D(QAbstractSocket);
1979 #if defined (QABSTRACTSOCKET_DEBUG)
1980 qDebug("QAbstractSocket::waitForConnected(%i)", msecs);
1983 if (state() == ConnectedState) {
1984 #if defined (QABSTRACTSOCKET_DEBUG)
1985 qDebug("QAbstractSocket::waitForConnected(%i) already connected", msecs);
1990 bool wasPendingClose = d->pendingClose;
1991 d->pendingClose = false;
1992 QElapsedTimer stopWatch;
1995 if (d->state == HostLookupState) {
1996 #if defined (QABSTRACTSOCKET_DEBUG)
1997 qDebug("QAbstractSocket::waitForConnected(%i) doing host name lookup", msecs);
1999 QHostInfo::abortHostLookup(d->hostLookupId);
2000 d->hostLookupId = -1;
2001 #ifndef QT_NO_BEARERMANAGEMENT
2002 QSharedPointer<QNetworkSession> networkSession;
2003 QVariant v(property("_q_networksession"));
2005 networkSession = qvariant_cast< QSharedPointer<QNetworkSession> >(v);
2006 d->_q_startConnecting(QHostInfoPrivate::fromName(d->hostName, networkSession));
2011 if (temp.setAddress(d->hostName)) {
2013 info.setAddresses(QList<QHostAddress>() << temp);
2014 d->_q_startConnecting(info);
2016 d->_q_startConnecting(QHostInfo::fromName(d->hostName));
2020 if (state() == UnconnectedState)
2021 return false; // connect not im progress anymore!
2023 bool timedOut = true;
2024 #if defined (QABSTRACTSOCKET_DEBUG)
2027 while (state() == ConnectingState && (msecs == -1 || stopWatch.elapsed() < msecs)) {
2028 int timeout = qt_timeout_value(msecs, stopWatch.elapsed());
2029 if (msecs != -1 && timeout > QT_CONNECT_TIMEOUT)
2030 timeout = QT_CONNECT_TIMEOUT;
2031 #if defined (QABSTRACTSOCKET_DEBUG)
2032 qDebug("QAbstractSocket::waitForConnected(%i) waiting %.2f secs for connection attempt #%i",
2033 msecs, timeout / 1000.0, attempt++);
2037 if (d->socketEngine && d->socketEngine->waitForWrite(timeout, &timedOut) && !timedOut) {
2038 d->_q_testConnection();
2040 d->_q_connectToNextAddress();
2044 if ((timedOut && state() != ConnectedState) || state() == ConnectingState) {
2045 d->socketError = SocketTimeoutError;
2046 d->state = UnconnectedState;
2047 emit stateChanged(d->state);
2048 d->resetSocketLayer();
2049 setErrorString(tr("Socket operation timed out"));
2052 #if defined (QABSTRACTSOCKET_DEBUG)
2053 qDebug("QAbstractSocket::waitForConnected(%i) == %s", msecs,
2054 state() == ConnectedState ? "true" : "false");
2056 if (state() != ConnectedState)
2058 if (wasPendingClose)
2059 disconnectFromHost();
2064 This function blocks until new data is available for reading and the
2065 \l{QIODevice::}{readyRead()} signal has been emitted. The function
2066 will timeout after \a msecs milliseconds; the default timeout is
2069 The function returns true if the readyRead() signal is emitted and
2070 there is new data available for reading; otherwise it returns false
2071 (if an error occurred or the operation timed out).
2073 \sa waitForBytesWritten()
2075 bool QAbstractSocket::waitForReadyRead(int msecs)
2077 Q_D(QAbstractSocket);
2078 #if defined (QABSTRACTSOCKET_DEBUG)
2079 qDebug("QAbstractSocket::waitForReadyRead(%i)", msecs);
2082 // require calling connectToHost() before waitForReadyRead()
2083 if (state() == UnconnectedState) {
2084 /* If all you have is a QIODevice pointer to an abstractsocket, you cannot check
2085 this, so you cannot avoid this warning. */
2086 // qWarning("QAbstractSocket::waitForReadyRead() is not allowed in UnconnectedState");
2090 QElapsedTimer stopWatch;
2093 // handle a socket in connecting state
2094 if (state() == HostLookupState || state() == ConnectingState) {
2095 if (!waitForConnected(msecs))
2099 Q_ASSERT(d->socketEngine);
2101 bool readyToRead = false;
2102 bool readyToWrite = false;
2103 if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
2104 qt_timeout_value(msecs, stopWatch.elapsed()))) {
2105 d->socketError = d->socketEngine->error();
2106 setErrorString(d->socketEngine->errorString());
2107 #if defined (QABSTRACTSOCKET_DEBUG)
2108 qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
2109 msecs, d->socketError, errorString().toLatin1().constData());
2111 emit error(d->socketError);
2112 if (d->socketError != SocketTimeoutError)
2118 if (d->canReadNotification())
2123 d->canWriteNotification();
2125 if (state() != ConnectedState)
2127 } while (msecs == -1 || qt_timeout_value(msecs, stopWatch.elapsed()) > 0);
2133 bool QAbstractSocket::waitForBytesWritten(int msecs)
2135 Q_D(QAbstractSocket);
2136 #if defined (QABSTRACTSOCKET_DEBUG)
2137 qDebug("QAbstractSocket::waitForBytesWritten(%i)", msecs);
2140 // require calling connectToHost() before waitForBytesWritten()
2141 if (state() == UnconnectedState) {
2142 qWarning("QAbstractSocket::waitForBytesWritten() is not allowed in UnconnectedState");
2146 if (d->writeBuffer.isEmpty())
2149 QElapsedTimer stopWatch;
2152 // handle a socket in connecting state
2153 if (state() == HostLookupState || state() == ConnectingState) {
2154 if (!waitForConnected(msecs))
2159 bool readyToRead = false;
2160 bool readyToWrite = false;
2161 if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
2162 qt_timeout_value(msecs, stopWatch.elapsed()))) {
2163 d->socketError = d->socketEngine->error();
2164 setErrorString(d->socketEngine->errorString());
2165 #if defined (QABSTRACTSOCKET_DEBUG)
2166 qDebug("QAbstractSocket::waitForBytesWritten(%i) failed (%i, %s)",
2167 msecs, d->socketError, errorString().toLatin1().constData());
2169 emit error(d->socketError);
2170 if (d->socketError != SocketTimeoutError)
2176 #if defined (QABSTRACTSOCKET_DEBUG)
2177 qDebug("QAbstractSocket::waitForBytesWritten calls canReadNotification");
2179 if(!d->canReadNotification())
2185 if (d->canWriteNotification()) {
2186 #if defined (QABSTRACTSOCKET_DEBUG)
2187 qDebug("QAbstractSocket::waitForBytesWritten returns true");
2193 if (state() != ConnectedState)
2200 Waits until the socket has disconnected, up to \a msecs
2201 milliseconds. If the connection has been disconnected, this
2202 function returns true; otherwise it returns false. In the case
2203 where it returns false, you can call error() to determine
2204 the cause of the error.
2206 The following example waits up to one second for a connection
2209 \snippet code/src_network_socket_qabstractsocket.cpp 1
2211 If msecs is -1, this function will not time out.
2213 \sa disconnectFromHost(), close()
2215 bool QAbstractSocket::waitForDisconnected(int msecs)
2217 Q_D(QAbstractSocket);
2219 // require calling connectToHost() before waitForDisconnected()
2220 if (state() == UnconnectedState) {
2221 qWarning("QAbstractSocket::waitForDisconnected() is not allowed in UnconnectedState");
2225 QElapsedTimer stopWatch;
2228 // handle a socket in connecting state
2229 if (state() == HostLookupState || state() == ConnectingState) {
2230 if (!waitForConnected(msecs))
2232 if (state() == UnconnectedState)
2237 bool readyToRead = false;
2238 bool readyToWrite = false;
2239 if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, state() == ConnectedState,
2240 !d->writeBuffer.isEmpty(),
2241 qt_timeout_value(msecs, stopWatch.elapsed()))) {
2242 d->socketError = d->socketEngine->error();
2243 setErrorString(d->socketEngine->errorString());
2244 #if defined (QABSTRACTSOCKET_DEBUG)
2245 qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
2246 msecs, d->socketError, errorString().toLatin1().constData());
2248 emit error(d->socketError);
2249 if (d->socketError != SocketTimeoutError)
2255 d->canReadNotification();
2257 d->canWriteNotification();
2259 if (state() == UnconnectedState)
2266 Aborts the current connection and resets the socket. Unlike disconnectFromHost(),
2267 this function immediately closes the socket, discarding any pending data in the
2270 \sa disconnectFromHost(), close()
2272 void QAbstractSocket::abort()
2274 Q_D(QAbstractSocket);
2275 #if defined (QABSTRACTSOCKET_DEBUG)
2276 qDebug("QAbstractSocket::abort()");
2278 if (d->state == UnconnectedState)
2281 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this)) {
2286 if (d->connectTimer) {
2287 d->connectTimer->stop();
2288 delete d->connectTimer;
2289 d->connectTimer = 0;
2292 d->writeBuffer.clear();
2293 d->abortCalled = true;
2299 bool QAbstractSocket::isSequential() const
2306 Returns true if no more data is currently
2307 available for reading; otherwise returns false.
2309 This function is most commonly used when reading data from the
2310 socket in a loop. For example:
2312 \snippet code/src_network_socket_qabstractsocket.cpp 2
2314 \sa bytesAvailable(), readyRead()
2316 bool QAbstractSocket::atEnd() const
2318 return QIODevice::atEnd() && (!isOpen() || d_func()->buffer.isEmpty());
2322 This function writes as much as possible from the internal write buffer to
2323 the underlying network socket, without blocking. If any data was written,
2324 this function returns true; otherwise false is returned.
2326 Call this function if you need QAbstractSocket to start sending buffered
2327 data immediately. The number of bytes successfully written depends on the
2328 operating system. In most cases, you do not need to call this function,
2329 because QAbstractSocket will start sending data automatically once control
2330 goes back to the event loop. In the absence of an event loop, call
2331 waitForBytesWritten() instead.
2333 \sa write(), waitForBytesWritten()
2335 // Note! docs copied to QSslSocket::flush()
2336 bool QAbstractSocket::flush()
2338 Q_D(QAbstractSocket);
2340 // Manual polymorphism; flush() isn't virtual, but QSslSocket overloads
2342 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
2343 return socket->flush();
2345 Q_CHECK_SOCKETENGINE(false);
2351 qint64 QAbstractSocket::readData(char *data, qint64 maxSize)
2353 Q_D(QAbstractSocket);
2355 // Check if the read notifier can be enabled again.
2356 if (d->socketEngine && !d->socketEngine->isReadNotificationEnabled() && d->socketEngine->isValid())
2357 d->socketEngine->setReadNotificationEnabled(true);
2362 // This is for a buffered QTcpSocket
2363 if (d->isBuffered && d->buffer.isEmpty())
2364 // if we're still connected, return 0 indicating there may be more data in the future
2365 // if we're not connected, return -1 indicating EOF
2366 return d->state == QAbstractSocket::ConnectedState ? qint64(0) : qint64(-1);
2368 if (!d->socketEngine)
2369 return -1; // no socket engine is probably EOF
2370 if (!d->socketEngine->isValid())
2371 return -1; // This is for unbuffered TCP when we already had been disconnected
2372 if (d->state != QAbstractSocket::ConnectedState)
2373 return -1; // This is for unbuffered TCP if we're not connected yet
2374 qint64 readBytes = d->socketEngine->read(data, maxSize);
2375 if (readBytes == -2) {
2376 // -2 from the engine means no bytes available (EAGAIN) so read more later
2378 } else if (readBytes < 0) {
2379 d->socketError = d->socketEngine->error();
2380 setErrorString(d->socketEngine->errorString());
2381 d->resetSocketLayer();
2382 d->state = QAbstractSocket::UnconnectedState;
2383 } else if (!d->socketEngine->isReadNotificationEnabled()) {
2384 // Only do this when there was no error
2385 d->socketEngine->setReadNotificationEnabled(true);
2388 #if defined (QABSTRACTSOCKET_DEBUG)
2389 qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld [engine]",
2390 data, qt_prettyDebug(data, 32, readBytes).data(), maxSize,
2399 qint64 QAbstractSocket::readLineData(char *data, qint64 maxlen)
2401 return QIODevice::readLineData(data, maxlen);
2406 qint64 QAbstractSocket::writeData(const char *data, qint64 size)
2408 Q_D(QAbstractSocket);
2409 if (d->state == QAbstractSocket::UnconnectedState) {
2410 d->socketError = QAbstractSocket::UnknownSocketError;
2411 setErrorString(tr("Socket is not connected"));
2415 if (!d->isBuffered && d->socketType == TcpSocket && d->writeBuffer.isEmpty()) {
2416 // This code is for the new Unbuffered QTcpSocket use case
2417 qint64 written = d->socketEngine->write(data, size);
2419 d->socketError = d->socketEngine->error();
2420 setErrorString(d->socketEngine->errorString());
2422 } else if (written < size) {
2423 // Buffer what was not written yet
2424 char *ptr = d->writeBuffer.reserve(size - written);
2425 memcpy(ptr, data + written, size - written);
2426 if (d->socketEngine)
2427 d->socketEngine->setWriteNotificationEnabled(true);
2429 return size; // size=actually written + what has been buffered
2430 } else if (!d->isBuffered && d->socketType != TcpSocket) {
2431 // This is for a QUdpSocket that was connect()ed
2432 qint64 written = d->socketEngine->write(data, size);
2434 d->socketError = d->socketEngine->error();
2435 setErrorString(d->socketEngine->errorString());
2436 } else if (!d->writeBuffer.isEmpty()) {
2437 d->socketEngine->setWriteNotificationEnabled(true);
2440 #if defined (QABSTRACTSOCKET_DEBUG)
2441 qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2442 qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2446 emit bytesWritten(written);
2450 // This is the code path for normal buffered QTcpSocket or
2451 // unbuffered QTcpSocket when there was already something in the
2452 // write buffer and therefore we could not do a direct engine write.
2453 // We just write to our write buffer and enable the write notifier
2454 // The write notifier then flush()es the buffer.
2456 char *ptr = d->writeBuffer.reserve(size);
2460 memcpy(ptr, data, size);
2462 qint64 written = size;
2464 if (d->socketEngine && !d->writeBuffer.isEmpty())
2465 d->socketEngine->setWriteNotificationEnabled(true);
2467 #if defined (QABSTRACTSOCKET_DEBUG)
2468 qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2469 qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2478 Sets the port on the local side of a connection to \a port.
2480 You can call this function in a subclass of QAbstractSocket to
2481 change the return value of the localPort() function after a
2482 connection has been established. This feature is commonly used by
2483 proxy connections for virtual connection settings.
2485 Note that this function does not bind the local port of the socket
2486 prior to a connection (e.g., QAbstractSocket::bind()).
2488 \sa localAddress(), setLocalAddress(), setPeerPort()
2490 void QAbstractSocket::setLocalPort(quint16 port)
2492 Q_D(QAbstractSocket);
2493 d->localPort = port;
2499 Sets the address on the local side of a connection to
2502 You can call this function in a subclass of QAbstractSocket to
2503 change the return value of the localAddress() function after a
2504 connection has been established. This feature is commonly used by
2505 proxy connections for virtual connection settings.
2507 Note that this function does not bind the local address of the socket
2508 prior to a connection (e.g., QAbstractSocket::bind()).
2510 \sa localAddress(), setLocalPort(), setPeerAddress()
2512 void QAbstractSocket::setLocalAddress(const QHostAddress &address)
2514 Q_D(QAbstractSocket);
2515 d->localAddress = address;
2521 Sets the port of the remote side of the connection to
2524 You can call this function in a subclass of QAbstractSocket to
2525 change the return value of the peerPort() function after a
2526 connection has been established. This feature is commonly used by
2527 proxy connections for virtual connection settings.
2529 \sa peerPort(), setPeerAddress(), setLocalPort()
2531 void QAbstractSocket::setPeerPort(quint16 port)
2533 Q_D(QAbstractSocket);
2540 Sets the address of the remote side of the connection
2543 You can call this function in a subclass of QAbstractSocket to
2544 change the return value of the peerAddress() function after a
2545 connection has been established. This feature is commonly used by
2546 proxy connections for virtual connection settings.
2548 \sa peerAddress(), setPeerPort(), setLocalAddress()
2550 void QAbstractSocket::setPeerAddress(const QHostAddress &address)
2552 Q_D(QAbstractSocket);
2553 d->peerAddress = address;
2559 Sets the host name of the remote peer to \a name.
2561 You can call this function in a subclass of QAbstractSocket to
2562 change the return value of the peerName() function after a
2563 connection has been established. This feature is commonly used by
2564 proxy connections for virtual connection settings.
2568 void QAbstractSocket::setPeerName(const QString &name)
2570 Q_D(QAbstractSocket);
2575 Closes the I/O device for the socket, disconnects the socket's connection with the
2576 host, closes the socket, and resets the name, address, port number and underlying
2579 See QIODevice::close() for a description of the actions that occur when an I/O
2584 void QAbstractSocket::close()
2586 Q_D(QAbstractSocket);
2587 #if defined(QABSTRACTSOCKET_DEBUG)
2588 qDebug("QAbstractSocket::close()");
2591 if (d->state != UnconnectedState) {
2592 d->closeCalled = true;
2593 disconnectFromHost();
2598 d->localAddress.clear();
2599 d->peerAddress.clear();
2600 d->peerName.clear();
2601 d->cachedSocketDescriptor = -1;
2605 Attempts to close the socket. If there is pending data waiting to
2606 be written, QAbstractSocket will enter ClosingState and wait
2607 until all data has been written. Eventually, it will enter
2608 UnconnectedState and emit the disconnected() signal.
2612 void QAbstractSocket::disconnectFromHost()
2614 Q_D(QAbstractSocket);
2615 #if defined(QABSTRACTSOCKET_DEBUG)
2616 qDebug("QAbstractSocket::disconnectFromHost()");
2619 if (d->state == UnconnectedState) {
2620 #if defined(QABSTRACTSOCKET_DEBUG)
2621 qDebug("QAbstractSocket::disconnectFromHost() was called on an unconnected socket");
2626 if (!d->abortCalled && (d->state == ConnectingState || d->state == HostLookupState)) {
2627 #if defined(QABSTRACTSOCKET_DEBUG)
2628 qDebug("QAbstractSocket::disconnectFromHost() but we're still connecting");
2630 d->pendingClose = true;
2634 // Disable and delete read notification
2635 if (d->socketEngine)
2636 d->socketEngine->setReadNotificationEnabled(false);
2638 if (d->abortCalled) {
2639 #if defined(QABSTRACTSOCKET_DEBUG)
2640 qDebug("QAbstractSocket::disconnectFromHost() aborting immediately");
2642 if (d->state == HostLookupState) {
2643 QHostInfo::abortHostLookup(d->hostLookupId);
2644 d->hostLookupId = -1;
2647 // Perhaps emit closing()
2648 if (d->state != ClosingState) {
2649 d->state = ClosingState;
2650 #if defined(QABSTRACTSOCKET_DEBUG)
2651 qDebug("QAbstractSocket::disconnectFromHost() emits stateChanged()(ClosingState)");
2653 emit stateChanged(d->state);
2655 #if defined(QABSTRACTSOCKET_DEBUG)
2656 qDebug("QAbstractSocket::disconnectFromHost() return from delayed close");
2660 // Wait for pending data to be written.
2661 if (d->socketEngine && d->socketEngine->isValid() && (d->writeBuffer.size() > 0
2662 || d->socketEngine->bytesToWrite() > 0)) {
2663 // hack: when we are waiting for the socket engine to write bytes (only
2664 // possible when using Socks5 or HTTP socket engine), then close
2665 // anyway after 2 seconds. This is to prevent a timeout on Mac, where we
2666 // sometimes just did not get the write notifier from the underlying
2667 // CFSocket and no progress was made.
2668 if (d->writeBuffer.size() == 0 && d->socketEngine->bytesToWrite() > 0) {
2669 if (!d->disconnectTimer) {
2670 d->disconnectTimer = new QTimer(this);
2671 connect(d->disconnectTimer, SIGNAL(timeout()), this,
2672 SLOT(_q_forceDisconnect()), Qt::DirectConnection);
2674 if (!d->disconnectTimer->isActive())
2675 d->disconnectTimer->start(2000);
2677 d->socketEngine->setWriteNotificationEnabled(true);
2679 #if defined(QABSTRACTSOCKET_DEBUG)
2680 qDebug("QAbstractSocket::disconnectFromHost() delaying disconnect");
2684 #if defined(QABSTRACTSOCKET_DEBUG)
2685 qDebug("QAbstractSocket::disconnectFromHost() disconnecting immediately");
2690 SocketState previousState = d->state;
2691 d->resetSocketLayer();
2692 d->state = UnconnectedState;
2693 emit stateChanged(d->state);
2694 emit readChannelFinished(); // we got an EOF
2696 // only emit disconnected if we were connected before
2697 if (previousState == ConnectedState || previousState == ClosingState)
2698 emit disconnected();
2702 d->localAddress.clear();
2703 d->peerAddress.clear();
2705 #if defined(QABSTRACTSOCKET_DEBUG)
2706 qDebug("QAbstractSocket::disconnectFromHost() disconnected!");
2709 if (d->closeCalled) {
2710 #if defined(QABSTRACTSOCKET_DEBUG)
2711 qDebug("QAbstractSocket::disconnectFromHost() closed!");
2714 d->writeBuffer.clear();
2720 Returns the size of the internal read buffer. This limits the
2721 amount of data that the client can receive before you call read()
2724 A read buffer size of 0 (the default) means that the buffer has
2725 no size limit, ensuring that no data is lost.
2727 \sa setReadBufferSize(), read()
2729 qint64 QAbstractSocket::readBufferSize() const
2731 return d_func()->readBufferMaxSize;
2735 Sets the size of QAbstractSocket's internal read buffer to be \a
2738 If the buffer size is limited to a certain size, QAbstractSocket
2739 won't buffer more than this size of data. Exceptionally, a buffer
2740 size of 0 means that the read buffer is unlimited and all
2741 incoming data is buffered. This is the default.
2743 This option is useful if you only read the data at certain points
2744 in time (e.g., in a real-time streaming application) or if you
2745 want to protect your socket against receiving too much data,
2746 which may eventually cause your application to run out of memory.
2748 Only QTcpSocket uses QAbstractSocket's internal buffer; QUdpSocket
2749 does not use any buffering at all, but rather relies on the
2750 implicit buffering provided by the operating system.
2751 Because of this, calling this function on QUdpSocket has no
2754 \sa readBufferSize(), read()
2756 void QAbstractSocket::setReadBufferSize(qint64 size)
2758 Q_D(QAbstractSocket);
2760 if (d->readBufferMaxSize == size)
2762 d->readBufferMaxSize = size;
2763 if (!d->readSocketNotifierCalled && d->socketEngine) {
2764 // ensure that the read notification is enabled if we've now got
2765 // room in the read buffer
2766 // but only if we're not inside canReadNotification -- that will take care on its own
2767 if ((size == 0 || d->buffer.size() < size) && d->state == QAbstractSocket::ConnectedState) // Do not change the notifier unless we are connected.
2768 d->socketEngine->setReadNotificationEnabled(true);
2773 Returns the state of the socket.
2777 QAbstractSocket::SocketState QAbstractSocket::state() const
2779 return d_func()->state;
2783 Sets the state of the socket to \a state.
2787 void QAbstractSocket::setSocketState(SocketState state)
2789 d_func()->state = state;
2793 Returns the socket type (TCP, UDP, or other).
2795 \sa QTcpSocket, QUdpSocket
2797 QAbstractSocket::SocketType QAbstractSocket::socketType() const
2799 return d_func()->socketType;
2803 Returns the type of error that last occurred.
2805 \sa state(), errorString()
2807 QAbstractSocket::SocketError QAbstractSocket::error() const
2809 return d_func()->socketError;
2813 Sets the type of error that last occurred to \a socketError.
2815 \sa setSocketState(), setErrorString()
2817 void QAbstractSocket::setSocketError(SocketError socketError)
2819 d_func()->socketError = socketError;
2822 #ifndef QT_NO_NETWORKPROXY
2826 Sets the explicit network proxy for this socket to \a networkProxy.
2828 To disable the use of a proxy for this socket, use the
2829 QNetworkProxy::NoProxy proxy type:
2831 \snippet code/src_network_socket_qabstractsocket.cpp 3
2833 The default value for the proxy is QNetworkProxy::DefaultProxy,
2834 which means the socket will use the application settings: if a
2835 proxy is set with QNetworkProxy::setApplicationProxy, it will use
2836 that; otherwise, if a factory is set with
2837 QNetworkProxyFactory::setApplicationProxyFactory, it will query
2838 that factory with type QNetworkProxyQuery::TcpSocket.
2840 \sa proxy(), QNetworkProxy, QNetworkProxyFactory::queryProxy()
2842 void QAbstractSocket::setProxy(const QNetworkProxy &networkProxy)
2844 Q_D(QAbstractSocket);
2845 d->proxy = networkProxy;
2851 Returns the network proxy for this socket.
2852 By default QNetworkProxy::DefaultProxy is used, which means this
2853 socket will query the default proxy settings for the application.
2855 \sa setProxy(), QNetworkProxy, QNetworkProxyFactory
2857 QNetworkProxy QAbstractSocket::proxy() const
2859 Q_D(const QAbstractSocket);
2862 #endif // QT_NO_NETWORKPROXY
2864 #ifndef QT_NO_DEBUG_STREAM
2865 Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketError error)
2868 case QAbstractSocket::ConnectionRefusedError:
2869 debug << "QAbstractSocket::ConnectionRefusedError";
2871 case QAbstractSocket::RemoteHostClosedError:
2872 debug << "QAbstractSocket::RemoteHostClosedError";
2874 case QAbstractSocket::HostNotFoundError:
2875 debug << "QAbstractSocket::HostNotFoundError";
2877 case QAbstractSocket::SocketAccessError:
2878 debug << "QAbstractSocket::SocketAccessError";
2880 case QAbstractSocket::SocketResourceError:
2881 debug << "QAbstractSocket::SocketResourceError";
2883 case QAbstractSocket::SocketTimeoutError:
2884 debug << "QAbstractSocket::SocketTimeoutError";
2886 case QAbstractSocket::DatagramTooLargeError:
2887 debug << "QAbstractSocket::DatagramTooLargeError";
2889 case QAbstractSocket::NetworkError:
2890 debug << "QAbstractSocket::NetworkError";
2892 case QAbstractSocket::AddressInUseError:
2893 debug << "QAbstractSocket::AddressInUseError";
2895 case QAbstractSocket::SocketAddressNotAvailableError:
2896 debug << "QAbstractSocket::SocketAddressNotAvailableError";
2898 case QAbstractSocket::UnsupportedSocketOperationError:
2899 debug << "QAbstractSocket::UnsupportedSocketOperationError";
2901 case QAbstractSocket::UnfinishedSocketOperationError:
2902 debug << "QAbstractSocket::UnfinishedSocketOperationError";
2904 case QAbstractSocket::ProxyAuthenticationRequiredError:
2905 debug << "QAbstractSocket::ProxyAuthenticationRequiredError";
2907 case QAbstractSocket::UnknownSocketError:
2908 debug << "QAbstractSocket::UnknownSocketError";
2910 case QAbstractSocket::ProxyConnectionRefusedError:
2911 debug << "QAbstractSocket::ProxyConnectionRefusedError";
2913 case QAbstractSocket::ProxyConnectionClosedError:
2914 debug << "QAbstractSocket::ProxyConnectionClosedError";
2916 case QAbstractSocket::ProxyConnectionTimeoutError:
2917 debug << "QAbstractSocket::ProxyConnectionTimeoutError";
2919 case QAbstractSocket::ProxyNotFoundError:
2920 debug << "QAbstractSocket::ProxyNotFoundError";
2922 case QAbstractSocket::ProxyProtocolError:
2923 debug << "QAbstractSocket::ProxyProtocolError";
2926 debug << "QAbstractSocket::SocketError(" << int(error) << ')';
2932 Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketState state)
2935 case QAbstractSocket::UnconnectedState:
2936 debug << "QAbstractSocket::UnconnectedState";
2938 case QAbstractSocket::HostLookupState:
2939 debug << "QAbstractSocket::HostLookupState";
2941 case QAbstractSocket::ConnectingState:
2942 debug << "QAbstractSocket::ConnectingState";
2944 case QAbstractSocket::ConnectedState:
2945 debug << "QAbstractSocket::ConnectedState";
2947 case QAbstractSocket::BoundState:
2948 debug << "QAbstractSocket::BoundState";
2950 case QAbstractSocket::ListeningState:
2951 debug << "QAbstractSocket::ListeningState";
2953 case QAbstractSocket::ClosingState:
2954 debug << "QAbstractSocket::ClosingState";
2957 debug << "QAbstractSocket::SocketState(" << int(state) << ')';
2966 #include "moc_qabstractsocket.cpp"