source: trunk/src/network/socket/qabstractsocket.cpp@ 754

Last change on this file since 754 was 651, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.2 sources.

File size: 88.4 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtNetwork module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42//#define QABSTRACTSOCKET_DEBUG
43
44/*!
45 \class QAbstractSocket
46
47 \brief The QAbstractSocket class provides the base functionality
48 common to all socket types.
49
50 \reentrant
51 \ingroup network
52 \inmodule QtNetwork
53
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:
57
58 \list
59 \i Instantiate QTcpSocket or QUdpSocket.
60 \i Create a native socket descriptor, instantiate
61 QAbstractSocket, and call setSocketDescriptor() to wrap the
62 native socket.
63 \endlist
64
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
71 important.
72
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
80 values.
81
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.
93
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
101 signal.
102
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().
111
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
120 will be emitted.
121
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.
126
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:
130
131 \list
132 \o waitForConnected() blocks until a connection has been established.
133
134 \o waitForReadyRead() blocks until new data is available for
135 reading.
136
137 \o waitForBytesWritten() blocks until one payload of data has been
138 written to the socket.
139
140 \o waitForDisconnected() blocks until the connection has closed.
141 \endlist
142
143 We show an example:
144
145 \snippet doc/src/snippets/network/tcpwait.cpp 0
146
147 If \l{QIODevice::}{waitForReadyRead()} returns false, the
148 connection has been closed or an error has occurred.
149
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.
157
158 QAbstractSocket can be used with QTextStream and QDataStream's
159 stream operators (operator<<() and operator>>()). There is one
160 issue to be aware of, though: You must make sure that enough data
161 is available before attempting to read it using operator>>().
162
163 \sa QFtp, QNetworkAccessManager, QTcpServer
164*/
165
166/*!
167 \fn void QAbstractSocket::hostFound()
168
169 This signal is emitted after connectToHost() has been called and
170 the host lookup has succeeded.
171
172 \sa connected()
173*/
174
175/*!
176 \fn void QAbstractSocket::connected()
177
178 This signal is emitted after connectToHost() has been called and
179 a connection has been successfully established.
180
181 \sa connectToHost(), disconnected()
182*/
183
184/*!
185 \fn void QAbstractSocket::disconnected()
186
187 This signal is emitted when the socket has been disconnected.
188
189 \warning If you need to delete the sender() of this signal in a slot connected
190 to it, use the \l{QObject::deleteLater()}{deleteLater()} function.
191
192 \sa connectToHost(), disconnectFromHost(), abort()
193*/
194
195/*!
196 \fn void QAbstractSocket::error(QAbstractSocket::SocketError socketError)
197
198 This signal is emitted after an error occurred. The \a socketError
199 parameter describes the type of error that occurred.
200
201 QAbstractSocket::SocketError is not a registered metatype, so for queued
202 connections, you will have to register it with Q_DECLARE_METATYPE() and
203 qRegisterMetaType().
204
205 \sa error(), errorString(), {Creating Custom Qt Types}
206*/
207
208/*!
209 \fn void QAbstractSocket::stateChanged(QAbstractSocket::SocketState socketState)
210
211 This signal is emitted whenever QAbstractSocket's state changes.
212 The \a socketState parameter is the new state.
213
214 QAbstractSocket::SocketState is not a registered metatype, so for queued
215 connections, you will have to register it with Q_REGISTER_METATYPE() and
216 qRegisterMetaType().
217
218 \sa state(), {Creating Custom Qt Types}
219*/
220
221/*!
222 \fn void QAbstractSocket::proxyAuthenticationRequired(const QNetworkProxy &proxy, QAuthenticator *authenticator)
223 \since 4.3
224
225 This signal can be emitted when a \a proxy that requires
226 authentication is used. The \a authenticator object can then be
227 filled in with the required details to allow authentication and
228 continue the connection.
229
230 \note It is not possible to use a QueuedConnection to connect to
231 this signal, as the connection will fail if the authenticator has
232 not been filled in with new information when the signal returns.
233
234 \sa QAuthenticator, QNetworkProxy
235*/
236
237/*!
238 \enum QAbstractSocket::NetworkLayerProtocol
239
240 This enum describes the network layer protocol values used in Qt.
241
242 \value IPv4Protocol IPv4
243 \value IPv6Protocol IPv6
244 \value UnknownNetworkLayerProtocol Other than IPv4 and IPv6
245
246 \sa QHostAddress::protocol()
247*/
248
249/*!
250 \enum QAbstractSocket::SocketType
251
252 This enum describes the transport layer protocol.
253
254 \value TcpSocket TCP
255 \value UdpSocket UDP
256 \value UnknownSocketType Other than TCP and UDP
257
258 \sa QAbstractSocket::socketType()
259*/
260
261/*!
262 \enum QAbstractSocket::SocketError
263
264 This enum describes the socket errors that can occur.
265
266 \value ConnectionRefusedError The connection was refused by the
267 peer (or timed out).
268 \value RemoteHostClosedError The remote host closed the
269 connection. Note that the client socket (i.e., this socket)
270 will be closed after the remote close notification has
271 been sent.
272 \value HostNotFoundError The host address was not found.
273 \value SocketAccessError The socket operation failed because the
274 application lacked the required privileges.
275 \value SocketResourceError The local system ran out of resources
276 (e.g., too many sockets).
277 \value SocketTimeoutError The socket operation timed out.
278 \value DatagramTooLargeError The datagram was larger than the
279 operating system's limit (which can be as low as 8192
280 bytes).
281 \value NetworkError An error occurred with the network (e.g., the
282 network cable was accidentally plugged out).
283 \value AddressInUseError The address specified to QUdpSocket::bind() is
284 already in use and was set to be exclusive.
285 \value SocketAddressNotAvailableError The address specified to
286 QUdpSocket::bind() does not belong to the host.
287 \value UnsupportedSocketOperationError The requested socket operation is
288 not supported by the local operating system (e.g., lack of
289 IPv6 support).
290 \value ProxyAuthenticationRequiredError The socket is using a proxy, and
291 the proxy requires authentication.
292 \value SslHandshakeFailedError The SSL/TLS handshake failed, so
293 the connection was closed (only used in QSslSocket)
294 \value UnfinishedSocketOperationError Used by QAbstractSocketEngine only,
295 The last operation attempted has not finished yet (still in progress in
296 the background).
297 \value ProxyConnectionRefusedError Could not contact the proxy server because
298 the connection to that server was denied
299 \value ProxyConnectionClosedError The connection to the proxy server was closed
300 unexpectedly (before the connection to the final peer was established)
301 \value ProxyConnectionTimeoutError The connection to the proxy server timed out
302 or the proxy server stopped responding in the authentication phase.
303 \value ProxyNotFoundError The proxy address set with setProxy() (or the application
304 proxy) was not found.
305 \value ProxyProtocolError The connection negotiation with the proxy server
306 because the response from the proxy server could not be understood.
307
308 \value UnknownSocketError An unidentified error occurred.
309 \sa QAbstractSocket::error()
310*/
311
312/*!
313 \enum QAbstractSocket::SocketState
314
315 This enum describes the different states in which a socket can be.
316
317 \value UnconnectedState The socket is not connected.
318 \value HostLookupState The socket is performing a host name lookup.
319 \value ConnectingState The socket has started establishing a connection.
320 \value ConnectedState A connection is established.
321 \value BoundState The socket is bound to an address and port (for servers).
322 \value ClosingState The socket is about to close (data may still
323 be waiting to be written).
324 \value ListeningState For internal use only.
325 \omitvalue Idle
326 \omitvalue HostLookup
327 \omitvalue Connecting
328 \omitvalue Connected
329 \omitvalue Closing
330 \omitvalue Connection
331
332 \sa QAbstractSocket::state()
333*/
334
335/*!
336 \enum QAbstractSocket::SocketOption
337 \since 4.6
338
339 This enum represents the options that can be set on a socket.
340 If desired, they can be set after having received the connected() signal from
341 the socket or after having received a new socket from a QTcpServer.
342
343 \value LowDelayOption Try to optimize the socket for low latency. For a QTcpSocket
344 this would set the TCP_NODELAY option and disable Nagle's algorithm. Set this to 1
345 to enable.
346 \value KeepAliveOption Set this to 1 to enable the SO_KEEPALIVE socket option
347
348 \sa QAbstractSocket::setSocketOption(), QAbstractSocket::socketOption()
349*/
350
351#include "qabstractsocket.h"
352#include "qabstractsocket_p.h"
353
354#include <qabstracteventdispatcher.h>
355#include <qdatetime.h>
356#include <qhostaddress.h>
357#include <qhostinfo.h>
358#include <qmetaobject.h>
359#include <qpointer.h>
360#include <qtimer.h>
361
362#ifndef QT_NO_OPENSSL
363#include <QtNetwork/qsslsocket.h>
364#endif
365
366#include <private/qthread_p.h>
367
368#ifdef QABSTRACTSOCKET_DEBUG
369#include <qdebug.h>
370#endif
371
372#include <time.h>
373
374#define Q_CHECK_SOCKETENGINE(returnValue) do { \
375 if (!d->socketEngine) { \
376 return returnValue; \
377 } } while (0)
378
379#ifndef QABSTRACTSOCKET_BUFFERSIZE
380#define QABSTRACTSOCKET_BUFFERSIZE 32768
381#endif
382#define QT_CONNECT_TIMEOUT 30000
383#define QT_TRANSFER_TIMEOUT 120000
384
385QT_BEGIN_NAMESPACE
386
387#if defined QABSTRACTSOCKET_DEBUG
388QT_BEGIN_INCLUDE_NAMESPACE
389#include <qstring.h>
390#include <ctype.h>
391QT_END_INCLUDE_NAMESPACE
392
393/*
394 Returns a human readable representation of the first \a len
395 characters in \a data.
396*/
397static QByteArray qt_prettyDebug(const char *data, int len, int maxLength)
398{
399 if (!data) return "(null)";
400 QByteArray out;
401 for (int i = 0; i < len; ++i) {
402 char c = data[i];
403 if (isprint(int(uchar(c)))) {
404 out += c;
405 } else switch (c) {
406 case '\n': out += "\\n"; break;
407 case '\r': out += "\\r"; break;
408 case '\t': out += "\\t"; break;
409 default:
410 QString tmp;
411 tmp.sprintf("\\%o", c);
412 out += tmp.toLatin1();
413 }
414 }
415
416 if (len < maxLength)
417 out += "...";
418
419 return out;
420}
421#endif
422
423static bool isProxyError(QAbstractSocket::SocketError error)
424{
425 switch (error) {
426 case QAbstractSocket::ProxyAuthenticationRequiredError:
427 case QAbstractSocket::ProxyConnectionRefusedError:
428 case QAbstractSocket::ProxyConnectionClosedError:
429 case QAbstractSocket::ProxyConnectionTimeoutError:
430 case QAbstractSocket::ProxyNotFoundError:
431 case QAbstractSocket::ProxyProtocolError:
432 return true;
433 default:
434 return false;
435 }
436}
437
438/*! \internal
439
440 Constructs a QAbstractSocketPrivate. Initializes all members.
441*/
442QAbstractSocketPrivate::QAbstractSocketPrivate()
443 : readSocketNotifierCalled(false),
444 readSocketNotifierState(false),
445 readSocketNotifierStateSet(false),
446 emittedReadyRead(false),
447 emittedBytesWritten(false),
448 abortCalled(false),
449 closeCalled(false),
450 pendingClose(false),
451 port(0),
452 localPort(0),
453 peerPort(0),
454 socketEngine(0),
455 cachedSocketDescriptor(-1),
456#ifdef Q_OS_LINUX
457 addToBytesAvailable(0),
458#endif
459 readBufferMaxSize(0),
460 readBuffer(QABSTRACTSOCKET_BUFFERSIZE),
461 writeBuffer(QABSTRACTSOCKET_BUFFERSIZE),
462 isBuffered(false),
463 blockingTimeout(30000),
464 connectTimer(0),
465 disconnectTimer(0),
466 connectTimeElapsed(0),
467 hostLookupId(-1),
468 socketType(QAbstractSocket::UnknownSocketType),
469 state(QAbstractSocket::UnconnectedState),
470 socketError(QAbstractSocket::UnknownSocketError)
471{
472}
473
474/*! \internal
475
476 Destructs the QAbstractSocket. If the socket layer is open, it
477 will be reset.
478*/
479QAbstractSocketPrivate::~QAbstractSocketPrivate()
480{
481}
482
483/*! \internal
484
485 Resets the socket layer, clears the read and write buffers and
486 deletes any socket notifiers.
487*/
488void QAbstractSocketPrivate::resetSocketLayer()
489{
490#if defined (QABSTRACTSOCKET_DEBUG)
491 qDebug("QAbstractSocketPrivate::resetSocketLayer()");
492#endif
493
494 if (socketEngine) {
495 socketEngine->close();
496 socketEngine->disconnect();
497 delete socketEngine;
498 socketEngine = 0;
499 cachedSocketDescriptor = -1;
500 }
501 if (connectTimer)
502 connectTimer->stop();
503 if (disconnectTimer)
504 disconnectTimer->stop();
505}
506
507/*! \internal
508
509 Initializes the socket layer to by of type \a type, using the
510 network layer protocol \a protocol. Resets the socket layer first
511 if it's already initialized. Sets up the socket notifiers.
512*/
513bool QAbstractSocketPrivate::initSocketLayer(QAbstractSocket::NetworkLayerProtocol protocol)
514{
515#ifdef QT_NO_NETWORKPROXY
516 // this is here to avoid a duplication of the call to createSocketEngine below
517 static const QNetworkProxy &proxyInUse = *(QNetworkProxy *)0;
518#endif
519
520 Q_Q(QAbstractSocket);
521#if defined (QABSTRACTSOCKET_DEBUG)
522 QString typeStr;
523 if (q->socketType() == QAbstractSocket::TcpSocket) typeStr = QLatin1String("TcpSocket");
524 else if (q->socketType() == QAbstractSocket::UdpSocket) typeStr = QLatin1String("UdpSocket");
525 else typeStr = QLatin1String("UnknownSocketType");
526 QString protocolStr;
527 if (protocol == QAbstractSocket::IPv4Protocol) protocolStr = QLatin1String("IPv4Protocol");
528 else if (protocol == QAbstractSocket::IPv6Protocol) protocolStr = QLatin1String("IPv6Protocol");
529 else protocolStr = QLatin1String("UnknownNetworkLayerProtocol");
530#endif
531
532 resetSocketLayer();
533 socketEngine = QAbstractSocketEngine::createSocketEngine(q->socketType(), proxyInUse, q);
534 if (!socketEngine) {
535 socketError = QAbstractSocket::UnsupportedSocketOperationError;
536 q->setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
537 return false;
538 }
539 if (!socketEngine->initialize(q->socketType(), protocol)) {
540#if defined (QABSTRACTSOCKET_DEBUG)
541 qDebug("QAbstractSocketPrivate::initSocketLayer(%s, %s) failed (%s)",
542 typeStr.toLatin1().constData(), protocolStr.toLatin1().constData(),
543 socketEngine->errorString().toLatin1().constData());
544#endif
545 socketError = socketEngine->error();
546 q->setErrorString(socketEngine->errorString());
547 return false;
548 }
549
550 if (threadData->eventDispatcher)
551 socketEngine->setReceiver(this);
552
553#if defined (QABSTRACTSOCKET_DEBUG)
554 qDebug("QAbstractSocketPrivate::initSocketLayer(%s, %s) success",
555 typeStr.toLatin1().constData(), protocolStr.toLatin1().constData());
556#endif
557 return true;
558}
559
560/*! \internal
561
562 Slot connected to the read socket notifier. This slot is called
563 when new data is available for reading, or when the socket has
564 been closed. Handles recursive calls.
565*/
566bool QAbstractSocketPrivate::canReadNotification()
567{
568 Q_Q(QAbstractSocket);
569#if defined (QABSTRACTSOCKET_DEBUG)
570 qDebug("QAbstractSocketPrivate::canReadNotification()");
571#endif
572
573 // Prevent recursive calls
574 if (readSocketNotifierCalled) {
575 if (!readSocketNotifierStateSet) {
576 readSocketNotifierStateSet = true;
577 readSocketNotifierState = socketEngine->isReadNotificationEnabled();
578 socketEngine->setReadNotificationEnabled(false);
579 }
580 }
581 readSocketNotifierCalled = true;
582
583 if (!isBuffered)
584 socketEngine->setReadNotificationEnabled(false);
585
586 // If buffered, read data from the socket into the read buffer
587 qint64 newBytes = 0;
588 if (isBuffered) {
589 // Return if there is no space in the buffer
590 if (readBufferMaxSize && readBuffer.size() >= readBufferMaxSize) {
591#if defined (QABSTRACTSOCKET_DEBUG)
592 qDebug("QAbstractSocketPrivate::canReadNotification() buffer is full");
593#endif
594 readSocketNotifierCalled = false;
595 return false;
596 }
597
598 // If reading from the socket fails after getting a read
599 // notification, close the socket.
600 newBytes = readBuffer.size();
601 if (!readFromSocket()) {
602#if defined (QABSTRACTSOCKET_DEBUG)
603 qDebug("QAbstractSocketPrivate::canReadNotification() disconnecting socket");
604#endif
605 q->disconnectFromHost();
606 readSocketNotifierCalled = false;
607 return false;
608 }
609 newBytes = readBuffer.size() - newBytes;
610
611 // If read buffer is full, disable the read socket notifier.
612 if (readBufferMaxSize && readBuffer.size() == readBufferMaxSize) {
613 socketEngine->setReadNotificationEnabled(false);
614 }
615 }
616
617 // only emit readyRead() when not recursing, and only if there is data available
618 bool hasData = newBytes > 0
619#ifndef QT_NO_UDPSOCKET
620 || (!isBuffered && socketEngine && socketEngine->hasPendingDatagrams())
621#endif
622 ;
623
624 if (!emittedReadyRead && hasData) {
625 emittedReadyRead = true;
626 emit q->readyRead();
627 emittedReadyRead = false;
628 }
629
630 // If we were closed as a result of the readyRead() signal,
631 // return.
632 if (state == QAbstractSocket::UnconnectedState || state == QAbstractSocket::ClosingState) {
633#if defined (QABSTRACTSOCKET_DEBUG)
634 qDebug("QAbstractSocketPrivate::canReadNotification() socket is closing - returning");
635#endif
636 readSocketNotifierCalled = false;
637 return true;
638 }
639
640 if (!hasData && socketEngine)
641 socketEngine->setReadNotificationEnabled(true);
642
643 // reset the read socket notifier state if we reentered inside the
644 // readyRead() connected slot.
645 if (readSocketNotifierStateSet && socketEngine &&
646 readSocketNotifierState != socketEngine->isReadNotificationEnabled()) {
647 socketEngine->setReadNotificationEnabled(readSocketNotifierState);
648 readSocketNotifierStateSet = false;
649 }
650 readSocketNotifierCalled = false;
651 return true;
652}
653
654/*! \internal
655
656 Slot connected to the write socket notifier. It's called during a
657 delayed connect or when the socket is ready for writing.
658*/
659bool QAbstractSocketPrivate::canWriteNotification()
660{
661#if defined (Q_OS_WIN)
662 if (socketEngine && socketEngine->isWriteNotificationEnabled())
663 socketEngine->setWriteNotificationEnabled(false);
664#endif
665
666#if defined (QABSTRACTSOCKET_DEBUG)
667 qDebug("QAbstractSocketPrivate::canWriteNotification() flushing");
668#endif
669 int tmp = writeBuffer.size();
670 flush();
671
672 if (socketEngine) {
673#if defined (Q_OS_WIN)
674 if (!writeBuffer.isEmpty())
675 socketEngine->setWriteNotificationEnabled(true);
676#else
677 if (writeBuffer.isEmpty() && socketEngine->bytesToWrite() == 0)
678 socketEngine->setWriteNotificationEnabled(false);
679#endif
680 }
681
682 return (writeBuffer.size() < tmp);
683}
684
685/*! \internal
686
687 Slot connected to a notification of connection status
688 change. Either we finished connecting or we failed to connect.
689*/
690void QAbstractSocketPrivate::connectionNotification()
691{
692 // If in connecting state, check if the connection has been
693 // established, otherwise flush pending data.
694 if (state == QAbstractSocket::ConnectingState) {
695#if defined (QABSTRACTSOCKET_DEBUG)
696 qDebug("QAbstractSocketPrivate::connectionNotification() testing connection");
697#endif
698 _q_testConnection();
699 }
700}
701
702/*! \internal
703
704 Writes pending data in the write buffers to the socket. The
705 function writes as much as it can without blocking.
706
707 It is usually invoked by canWriteNotification after one or more
708 calls to write().
709
710 Emits bytesWritten().
711*/
712bool QAbstractSocketPrivate::flush()
713{
714 Q_Q(QAbstractSocket);
715 if (!socketEngine || !socketEngine->isValid() || (writeBuffer.isEmpty()
716 && socketEngine->bytesToWrite() == 0)) {
717#if defined (QABSTRACTSOCKET_DEBUG)
718 qDebug("QAbstractSocketPrivate::flush() nothing to do: valid ? %s, writeBuffer.isEmpty() ? %s",
719 socketEngine->isValid() ? "yes" : "no", writeBuffer.isEmpty() ? "yes" : "no");
720#endif
721
722 // this covers the case when the buffer was empty, but we had to wait for the socket engine to finish
723 if (state == QAbstractSocket::ClosingState)
724 q->disconnectFromHost();
725
726 return false;
727 }
728
729 int nextSize = writeBuffer.nextDataBlockSize();
730 const char *ptr = writeBuffer.readPointer();
731
732 // Attempt to write it all in one chunk.
733 qint64 written = socketEngine->write(ptr, nextSize);
734 if (written < 0) {
735 socketError = socketEngine->error();
736 q->setErrorString(socketEngine->errorString());
737 emit q->error(socketError);
738 // an unexpected error so close the socket.
739#if defined (QABSTRACTSOCKET_DEBUG)
740 qDebug() << "QAbstractSocketPrivate::flush() write error, aborting." << socketEngine->errorString();
741#endif
742 q->abort();
743 return false;
744 }
745
746#if defined (QABSTRACTSOCKET_DEBUG)
747 qDebug("QAbstractSocketPrivate::flush() %lld bytes written to the network",
748 written);
749#endif
750
751 // Remove what we wrote so far.
752 writeBuffer.free(written);
753 if (written > 0) {
754 // Don't emit bytesWritten() recursively.
755 if (!emittedBytesWritten) {
756 emittedBytesWritten = true;
757 emit q->bytesWritten(written);
758 emittedBytesWritten = false;
759 }
760 }
761
762 if (writeBuffer.isEmpty() && socketEngine && socketEngine->isWriteNotificationEnabled()
763 && !socketEngine->bytesToWrite())
764 socketEngine->setWriteNotificationEnabled(false);
765 if (state == QAbstractSocket::ClosingState)
766 q->disconnectFromHost();
767
768 return true;
769}
770
771#ifndef QT_NO_NETWORKPROXY
772/*! \internal
773
774 Resolve the proxy to its final value.
775*/
776void QAbstractSocketPrivate::resolveProxy(const QString &hostname, quint16 port)
777{
778 QHostAddress parsed;
779 if (hostname == QLatin1String("localhost")
780 || hostname.startsWith(QLatin1String("localhost."))
781 || (parsed.setAddress(hostname)
782 && (parsed == QHostAddress::LocalHost
783 || parsed == QHostAddress::LocalHostIPv6))) {
784 proxyInUse = QNetworkProxy::NoProxy;
785 return;
786 }
787
788 QList<QNetworkProxy> proxies;
789
790 if (proxy.type() != QNetworkProxy::DefaultProxy) {
791 // a non-default proxy was set with setProxy
792 proxies << proxy;
793 } else {
794 // try the application settings instead
795 QNetworkProxyQuery query(hostname, port, QString(),
796 socketType == QAbstractSocket::TcpSocket ?
797 QNetworkProxyQuery::TcpSocket :
798 QNetworkProxyQuery::UdpSocket);
799 proxies = QNetworkProxyFactory::proxyForQuery(query);
800 }
801
802 // return the first that we can use
803 foreach (const QNetworkProxy &p, proxies) {
804 if (socketType == QAbstractSocket::UdpSocket &&
805 (p.capabilities() & QNetworkProxy::UdpTunnelingCapability) == 0)
806 continue;
807
808 if (socketType == QAbstractSocket::TcpSocket &&
809 (p.capabilities() & QNetworkProxy::TunnelingCapability) == 0)
810 continue;
811
812 proxyInUse = p;
813 return;
814 }
815
816 // no proxy found
817 // DefaultProxy here will raise an error
818 proxyInUse = QNetworkProxy();
819}
820
821/*!
822 \internal
823
824 Starts the connection to \a host, like _q_startConnecting below,
825 but without hostname resolution.
826*/
827void QAbstractSocketPrivate::startConnectingByName(const QString &host)
828{
829 Q_Q(QAbstractSocket);
830 if (state == QAbstractSocket::ConnectingState || state == QAbstractSocket::ConnectedState)
831 return;
832
833#if defined(QABSTRACTSOCKET_DEBUG)
834 qDebug("QAbstractSocketPrivate::startConnectingByName(host == %s)", qPrintable(host));
835#endif
836
837 // ### Let the socket engine drive this?
838 state = QAbstractSocket::ConnectingState;
839 emit q->stateChanged(state);
840
841 connectTimeElapsed = 0;
842
843 if (initSocketLayer(QAbstractSocket::UnknownNetworkLayerProtocol)) {
844 if (socketEngine->connectToHostByName(host, port) ||
845 socketEngine->state() == QAbstractSocket::ConnectingState) {
846 cachedSocketDescriptor = socketEngine->socketDescriptor();
847
848 return;
849 }
850
851 // failed to connect
852 socketError = socketEngine->error();
853 q->setErrorString(socketEngine->errorString());
854 }
855
856 state = QAbstractSocket::UnconnectedState;
857 emit q->error(socketError);
858 emit q->stateChanged(state);
859}
860
861#endif
862
863/*! \internal
864
865 Slot connected to QHostInfo::lookupHost() in connectToHost(). This
866 function starts the process of connecting to any number of
867 candidate IP addresses for the host, if it was found. Calls
868 _q_connectToNextAddress().
869*/
870void QAbstractSocketPrivate::_q_startConnecting(const QHostInfo &hostInfo)
871{
872 Q_Q(QAbstractSocket);
873 if (state != QAbstractSocket::HostLookupState)
874 return;
875
876 if (hostLookupId != -1 && hostLookupId != hostInfo.lookupId()) {
877 qWarning("QAbstractSocketPrivate::_q_startConnecting() received hostInfo for wrong lookup ID %d expected %d", hostInfo.lookupId(), hostLookupId);
878 }
879
880 addresses = hostInfo.addresses();
881
882#if defined(QABSTRACTSOCKET_DEBUG)
883 QString s = QLatin1String("{");
884 for (int i = 0; i < addresses.count(); ++i) {
885 if (i != 0) s += QLatin1String(", ");
886 s += addresses.at(i).toString();
887 }
888 s += QLatin1Char('}');
889 qDebug("QAbstractSocketPrivate::_q_startConnecting(hostInfo == %s)", s.toLatin1().constData());
890#endif
891
892 // Try all addresses twice.
893 addresses += addresses;
894
895 // If there are no addresses in the host list, report this to the
896 // user.
897 if (addresses.isEmpty()) {
898#if defined(QABSTRACTSOCKET_DEBUG)
899 qDebug("QAbstractSocketPrivate::_q_startConnecting(), host not found");
900#endif
901 state = QAbstractSocket::UnconnectedState;
902 socketError = QAbstractSocket::HostNotFoundError;
903 q->setErrorString(QAbstractSocket::tr("Host not found"));
904 emit q->stateChanged(state);
905 emit q->error(QAbstractSocket::HostNotFoundError);
906 return;
907 }
908
909 // Enter Connecting state (see also sn_write, which is called by
910 // the write socket notifier after connect())
911 state = QAbstractSocket::ConnectingState;
912 emit q->stateChanged(state);
913
914 // Report the successful host lookup
915 emit q->hostFound();
916
917 // Reset the total time spent connecting.
918 connectTimeElapsed = 0;
919
920 // The addresses returned by the lookup will be tested one after
921 // another by _q_connectToNextAddress().
922 _q_connectToNextAddress();
923}
924
925/*! \internal
926
927 Called by a queued or direct connection from _q_startConnecting() or
928 _q_testConnection(), this function takes the first address of the
929 pending addresses list and tries to connect to it. If the
930 connection succeeds, QAbstractSocket will emit
931 connected(). Otherwise, error(ConnectionRefusedError) or
932 error(SocketTimeoutError) is emitted.
933*/
934void QAbstractSocketPrivate::_q_connectToNextAddress()
935{
936 Q_Q(QAbstractSocket);
937 do {
938 // Check for more pending addresses
939 if (addresses.isEmpty()) {
940#if defined(QABSTRACTSOCKET_DEBUG)
941 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), all addresses failed.");
942#endif
943 state = QAbstractSocket::UnconnectedState;
944 if (socketEngine) {
945 if ((socketEngine->error() == QAbstractSocket::UnknownSocketError
946#ifdef Q_OS_AIX
947 // On AIX, the second connect call will result in EINVAL and not
948 // ECONNECTIONREFUSED; although the meaning is the same.
949 || socketEngine->error() == QAbstractSocket::UnsupportedSocketOperationError
950#endif
951 ) && socketEngine->state() == QAbstractSocket::ConnectingState) {
952 socketError = QAbstractSocket::ConnectionRefusedError;
953 q->setErrorString(QAbstractSocket::tr("Connection refused"));
954 } else {
955 socketError = socketEngine->error();
956 q->setErrorString(socketEngine->errorString());
957 }
958 } else {
959// socketError = QAbstractSocket::ConnectionRefusedError;
960// q->setErrorString(QAbstractSocket::tr("Connection refused"));
961 }
962 emit q->stateChanged(state);
963 emit q->error(socketError);
964 return;
965 }
966
967 // Pick the first host address candidate
968 host = addresses.takeFirst();
969#if defined(QABSTRACTSOCKET_DEBUG)
970 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), connecting to %s:%i, %d left to try",
971 host.toString().toLatin1().constData(), port, addresses.count());
972#endif
973
974#if defined(QT_NO_IPV6)
975 if (host.protocol() == QAbstractSocket::IPv6Protocol) {
976 // If we have no IPv6 support, then we will not be able to
977 // connect. So we just pretend we didn't see this address.
978#if defined(QABSTRACTSOCKET_DEBUG)
979 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), skipping IPv6 entry");
980#endif
981 continue;
982 }
983#endif
984
985 if (!initSocketLayer(host.protocol())) {
986 // hope that the next address is better
987#if defined(QABSTRACTSOCKET_DEBUG)
988 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), failed to initialize sock layer");
989#endif
990 continue;
991 }
992
993 // Tries to connect to the address. If it succeeds immediately
994 // (localhost address on BSD or any UDP connect), emit
995 // connected() and return.
996 if (socketEngine->connectToHost(host, port)) {
997 //_q_testConnection();
998 fetchConnectionParameters();
999 return;
1000 }
1001
1002 // cache the socket descriptor even if we're not fully connected yet
1003 cachedSocketDescriptor = socketEngine->socketDescriptor();
1004
1005 // Check that we're in delayed connection state. If not, try
1006 // the next address
1007 if (socketEngine->state() != QAbstractSocket::ConnectingState) {
1008#if defined(QABSTRACTSOCKET_DEBUG)
1009 qDebug("QAbstractSocketPrivate::_q_connectToNextAddress(), connection failed (%s)",
1010 socketEngine->errorString().toLatin1().constData());
1011#endif
1012 continue;
1013 }
1014
1015 // Start the connect timer.
1016 if (threadData->eventDispatcher) {
1017 if (!connectTimer) {
1018 connectTimer = new QTimer(q);
1019 QObject::connect(connectTimer, SIGNAL(timeout()),
1020 q, SLOT(_q_abortConnectionAttempt()),
1021 Qt::DirectConnection);
1022 }
1023 connectTimer->start(QT_CONNECT_TIMEOUT);
1024 }
1025
1026 // Wait for a write notification that will eventually call
1027 // _q_testConnection().
1028 socketEngine->setWriteNotificationEnabled(true);
1029 break;
1030 } while (state != QAbstractSocket::ConnectedState);
1031}
1032
1033/*! \internal
1034
1035 Tests if a connection has been established. If it has, connected()
1036 is emitted. Otherwise, _q_connectToNextAddress() is invoked.
1037*/
1038void QAbstractSocketPrivate::_q_testConnection()
1039{
1040 if (socketEngine) {
1041 if (threadData->eventDispatcher) {
1042 if (connectTimer)
1043 connectTimer->stop();
1044 }
1045
1046 if (socketEngine->state() == QAbstractSocket::ConnectedState) {
1047 // Fetch the parameters if our connection is completed;
1048 // otherwise, fall out and try the next address.
1049 fetchConnectionParameters();
1050 if (pendingClose) {
1051 q_func()->disconnectFromHost();
1052 pendingClose = false;
1053 }
1054 return;
1055 }
1056
1057 // don't retry the other addresses if we had a proxy error
1058 if (isProxyError(socketEngine->error()))
1059 addresses.clear();
1060 }
1061
1062 if (threadData->eventDispatcher) {
1063 if (connectTimer)
1064 connectTimer->stop();
1065 }
1066
1067#if defined(QABSTRACTSOCKET_DEBUG)
1068 qDebug("QAbstractSocketPrivate::_q_testConnection() connection failed,"
1069 " checking for alternative addresses");
1070#endif
1071 _q_connectToNextAddress();
1072}
1073
1074/*! \internal
1075
1076 This function is called after a certain number of seconds has
1077 passed while waiting for a connection. It simply tests the
1078 connection, and continues to the next address if the connection
1079 failed.
1080*/
1081void QAbstractSocketPrivate::_q_abortConnectionAttempt()
1082{
1083 Q_Q(QAbstractSocket);
1084#if defined(QABSTRACTSOCKET_DEBUG)
1085 qDebug("QAbstractSocketPrivate::_q_abortConnectionAttempt() (timed out)");
1086#endif
1087 if (socketEngine)
1088 socketEngine->setWriteNotificationEnabled(false);
1089
1090 connectTimer->stop();
1091
1092 if (addresses.isEmpty()) {
1093 state = QAbstractSocket::UnconnectedState;
1094 socketError = QAbstractSocket::SocketTimeoutError;
1095 q->setErrorString(QAbstractSocket::tr("Connection timed out"));
1096 emit q->stateChanged(state);
1097 emit q->error(socketError);
1098 } else {
1099 _q_connectToNextAddress();
1100 }
1101}
1102
1103void QAbstractSocketPrivate::_q_forceDisconnect()
1104{
1105 Q_Q(QAbstractSocket);
1106 if (socketEngine && socketEngine->isValid() && state == QAbstractSocket::ClosingState) {
1107 socketEngine->close();
1108 q->disconnectFromHost();
1109 }
1110}
1111
1112/*! \internal
1113
1114 Reads data from the socket layer into the read buffer. Returns
1115 true on success; otherwise false.
1116*/
1117bool QAbstractSocketPrivate::readFromSocket()
1118{
1119 Q_Q(QAbstractSocket);
1120 // Find how many bytes we can read from the socket layer.
1121 qint64 bytesToRead = socketEngine->bytesAvailable();
1122#ifdef Q_OS_LINUX
1123 if (bytesToRead > 0) // ### See setSocketDescriptor()
1124 bytesToRead += addToBytesAvailable;
1125#endif
1126 if (bytesToRead == 0) {
1127 // Under heavy load, certain conditions can trigger read notifications
1128 // for socket notifiers on which there is no activity. If we continue
1129 // to read 0 bytes from the socket, we will trigger behavior similar
1130 // to that which signals a remote close. When we hit this condition,
1131 // we try to read 4k of data from the socket, which will give us either
1132 // an EAGAIN/EWOULDBLOCK if the connection is alive (i.e., the remote
1133 // host has _not_ disappeared).
1134 bytesToRead = 4096;
1135 }
1136 if (readBufferMaxSize && bytesToRead > (readBufferMaxSize - readBuffer.size()))
1137 bytesToRead = readBufferMaxSize - readBuffer.size();
1138
1139#if defined(QABSTRACTSOCKET_DEBUG)
1140 qDebug("QAbstractSocketPrivate::readFromSocket() about to read %d bytes",
1141 int(bytesToRead));
1142#endif
1143
1144 // Read from the socket, store data in the read buffer.
1145 char *ptr = readBuffer.reserve(bytesToRead);
1146 qint64 readBytes = socketEngine->read(ptr, bytesToRead);
1147 if (readBytes == -2) {
1148 // No bytes currently available for reading.
1149 readBuffer.chop(bytesToRead);
1150 return true;
1151 }
1152 readBuffer.chop(int(bytesToRead - (readBytes < 0 ? qint64(0) : readBytes)));
1153#if defined(QABSTRACTSOCKET_DEBUG)
1154 qDebug("QAbstractSocketPrivate::readFromSocket() got %d bytes, buffer size = %d",
1155 int(readBytes), readBuffer.size());
1156#endif
1157
1158 if (!socketEngine->isValid()) {
1159 socketError = socketEngine->error();
1160 q->setErrorString(socketEngine->errorString());
1161 emit q->error(socketError);
1162#if defined(QABSTRACTSOCKET_DEBUG)
1163 qDebug("QAbstractSocketPrivate::readFromSocket() read failed: %s",
1164 q->errorString().toLatin1().constData());
1165#endif
1166 resetSocketLayer();
1167 return false;
1168 }
1169
1170 return true;
1171}
1172
1173/*! \internal
1174
1175 Sets up the internal state after the connection has succeeded.
1176*/
1177void QAbstractSocketPrivate::fetchConnectionParameters()
1178{
1179 Q_Q(QAbstractSocket);
1180
1181 peerName = hostName;
1182 if (socketEngine) {
1183 socketEngine->setReadNotificationEnabled(true);
1184 socketEngine->setWriteNotificationEnabled(true);
1185 localPort = socketEngine->localPort();
1186 peerPort = socketEngine->peerPort();
1187 localAddress = socketEngine->localAddress();
1188 peerAddress = socketEngine->peerAddress();
1189 cachedSocketDescriptor = socketEngine->socketDescriptor();
1190 }
1191
1192 state = QAbstractSocket::ConnectedState;
1193 emit q->stateChanged(state);
1194 emit q->connected();
1195
1196#if defined(QABSTRACTSOCKET_DEBUG)
1197 qDebug("QAbstractSocketPrivate::fetchConnectionParameters() connection to %s:%i established",
1198 host.toString().toLatin1().constData(), port);
1199#endif
1200}
1201
1202/*! \internal
1203
1204 Constructs a new abstract socket of type \a socketType. The \a
1205 parent argument is passed to QObject's constructor.
1206*/
1207QAbstractSocket::QAbstractSocket(SocketType socketType,
1208 QAbstractSocketPrivate &dd, QObject *parent)
1209 : QIODevice(dd, parent)
1210{
1211 Q_D(QAbstractSocket);
1212#if defined(QABSTRACTSOCKET_DEBUG)
1213 qDebug("QAbstractSocket::QAbstractSocket(%sSocket, QAbstractSocketPrivate == %p, parent == %p)",
1214 socketType == TcpSocket ? "Tcp" : socketType == UdpSocket
1215 ? "Udp" : "Unknown", &dd, parent);
1216#endif
1217 d->socketType = socketType;
1218}
1219
1220/*!
1221 Creates a new abstract socket of type \a socketType. The \a
1222 parent argument is passed to QObject's constructor.
1223
1224 \sa socketType(), QTcpSocket, QUdpSocket
1225*/
1226QAbstractSocket::QAbstractSocket(SocketType socketType, QObject *parent)
1227 : QIODevice(*new QAbstractSocketPrivate, parent)
1228{
1229 Q_D(QAbstractSocket);
1230#if defined(QABSTRACTSOCKET_DEBUG)
1231 qDebug("QAbstractSocket::QAbstractSocket(%p)", parent);
1232#endif
1233 d->socketType = socketType;
1234}
1235
1236/*!
1237 Destroys the socket.
1238*/
1239QAbstractSocket::~QAbstractSocket()
1240{
1241 Q_D(QAbstractSocket);
1242#if defined(QABSTRACTSOCKET_DEBUG)
1243 qDebug("QAbstractSocket::~QAbstractSocket()");
1244#endif
1245 if (d->state != UnconnectedState)
1246 abort();
1247}
1248
1249/*!
1250 Returns true if the socket is valid and ready for use; otherwise
1251 returns false.
1252
1253 \bold{Note:} The socket's state must be ConnectedState before reading and
1254 writing can occur.
1255
1256 \sa state()
1257*/
1258bool QAbstractSocket::isValid() const
1259{
1260 return d_func()->socketEngine ? d_func()->socketEngine->isValid() : isOpen();
1261}
1262
1263/*!
1264 Attempts to make a connection to \a hostName on the given \a port.
1265
1266 The socket is opened in the given \a openMode and first enters
1267 HostLookupState, then performs a host name lookup of \a hostName.
1268 If the lookup succeeds, hostFound() is emitted and QAbstractSocket
1269 enters ConnectingState. It then attempts to connect to the address
1270 or addresses returned by the lookup. Finally, if a connection is
1271 established, QAbstractSocket enters ConnectedState and
1272 emits connected().
1273
1274 At any point, the socket can emit error() to signal that an error
1275 occurred.
1276
1277 \a hostName may be an IP address in string form (e.g.,
1278 "43.195.83.32"), or it may be a host name (e.g.,
1279 "example.com"). QAbstractSocket will do a lookup only if
1280 required. \a port is in native byte order.
1281
1282 \sa state(), peerName(), peerAddress(), peerPort(), waitForConnected()
1283*/
1284void QAbstractSocket::connectToHost(const QString &hostName, quint16 port,
1285 OpenMode openMode)
1286{
1287 QMetaObject::invokeMethod(this, "connectToHostImplementation",
1288 Qt::DirectConnection,
1289 Q_ARG(QString, hostName),
1290 Q_ARG(quint16, port),
1291 Q_ARG(OpenMode, openMode));
1292}
1293
1294/*!
1295 \since 4.1
1296
1297 Contains the implementation of connectToHost().
1298
1299 Attempts to make a connection to \a hostName on the given \a
1300 port. The socket is opened in the given \a openMode.
1301*/
1302void QAbstractSocket::connectToHostImplementation(const QString &hostName, quint16 port,
1303 OpenMode openMode)
1304{
1305 Q_D(QAbstractSocket);
1306#if defined(QABSTRACTSOCKET_DEBUG)
1307 qDebug("QAbstractSocket::connectToHost(\"%s\", %i, %i)...", qPrintable(hostName), port,
1308 (int) openMode);
1309#endif
1310
1311 if (d->state == ConnectedState || d->state == ConnectingState
1312 || d->state == ClosingState || d->state == HostLookupState) {
1313 qWarning("QAbstractSocket::connectToHost() called when already looking up or connecting/connected to \"%s\"", qPrintable(hostName));
1314 return;
1315 }
1316
1317 d->hostName = hostName;
1318 d->port = port;
1319 d->state = UnconnectedState;
1320 d->readBuffer.clear();
1321 d->writeBuffer.clear();
1322 d->abortCalled = false;
1323 d->closeCalled = false;
1324 d->pendingClose = false;
1325 d->localPort = 0;
1326 d->peerPort = 0;
1327 d->localAddress.clear();
1328 d->peerAddress.clear();
1329 d->peerName = hostName;
1330#ifdef Q_OS_LINUX
1331 // ### See setSocketDescriptor().
1332 d->addToBytesAvailable = 0;
1333#endif
1334 if (d->hostLookupId != -1) {
1335 QHostInfo::abortHostLookup(d->hostLookupId);
1336 d->hostLookupId = -1;
1337 }
1338
1339#ifndef QT_NO_NETWORKPROXY
1340 // Get the proxy information
1341 d->resolveProxy(hostName, port);
1342 if (d->proxyInUse.type() == QNetworkProxy::DefaultProxy) {
1343 // failed to setup the proxy
1344 d->socketError = QAbstractSocket::UnsupportedSocketOperationError;
1345 setErrorString(QAbstractSocket::tr("Operation on socket is not supported"));
1346 emit error(d->socketError);
1347 return;
1348 }
1349#endif
1350
1351 if (!d_func()->isBuffered)
1352 openMode |= QAbstractSocket::Unbuffered;
1353 QIODevice::open(openMode);
1354 d->state = HostLookupState;
1355 emit stateChanged(d->state);
1356
1357 QHostAddress temp;
1358 if (temp.setAddress(hostName)) {
1359 QHostInfo info;
1360 info.setAddresses(QList<QHostAddress>() << temp);
1361 d->_q_startConnecting(info);
1362#ifndef QT_NO_NETWORKPROXY
1363 } else if (d->proxyInUse.capabilities() & QNetworkProxy::HostNameLookupCapability) {
1364 // the proxy supports connection by name, so use it
1365 d->startConnectingByName(hostName);
1366 return;
1367#endif
1368 } else {
1369 if (d->threadData->eventDispatcher)
1370 d->hostLookupId = QHostInfo::lookupHost(hostName, this, SLOT(_q_startConnecting(QHostInfo)));
1371 }
1372
1373#if defined(QABSTRACTSOCKET_DEBUG)
1374 qDebug("QAbstractSocket::connectToHost(\"%s\", %i) == %s%s", hostName.toLatin1().constData(), port,
1375 (d->state == ConnectedState) ? "true" : "false",
1376 (d->state == ConnectingState || d->state == HostLookupState)
1377 ? " (connection in progress)" : "");
1378#endif
1379}
1380
1381/*! \overload
1382
1383 Attempts to make a connection to \a address on port \a port.
1384*/
1385void QAbstractSocket::connectToHost(const QHostAddress &address, quint16 port,
1386 OpenMode openMode)
1387{
1388#if defined(QABSTRACTSOCKET_DEBUG)
1389 qDebug("QAbstractSocket::connectToHost([%s], %i, %i)...",
1390 address.toString().toLatin1().constData(), port, (int) openMode);
1391#endif
1392 connectToHost(address.toString(), port, openMode);
1393}
1394
1395/*!
1396 Returns the number of bytes that are waiting to be written. The
1397 bytes are written when control goes back to the event loop or
1398 when flush() is called.
1399
1400 \sa bytesAvailable(), flush()
1401*/
1402qint64 QAbstractSocket::bytesToWrite() const
1403{
1404 Q_D(const QAbstractSocket);
1405#if defined(QABSTRACTSOCKET_DEBUG)
1406 qDebug("QAbstractSocket::bytesToWrite() == %i", d->writeBuffer.size());
1407#endif
1408 return (qint64)d->writeBuffer.size();
1409}
1410
1411/*!
1412 Returns the number of incoming bytes that are waiting to be read.
1413
1414 \sa bytesToWrite(), read()
1415*/
1416qint64 QAbstractSocket::bytesAvailable() const
1417{
1418 Q_D(const QAbstractSocket);
1419 qint64 available = QIODevice::bytesAvailable();
1420 if (d->isBuffered)
1421 available += (qint64) d->readBuffer.size();
1422 else if (d->socketEngine && d->socketEngine->isValid())
1423 available += d->socketEngine->bytesAvailable();
1424#if defined(QABSTRACTSOCKET_DEBUG)
1425 qDebug("QAbstractSocket::bytesAvailable() == %llu", available);
1426#endif
1427 return available;
1428}
1429
1430/*!
1431 Returns the host port number (in native byte order) of the local
1432 socket if available; otherwise returns 0.
1433
1434 \sa localAddress(), peerPort(), setLocalPort()
1435*/
1436quint16 QAbstractSocket::localPort() const
1437{
1438 Q_D(const QAbstractSocket);
1439 return d->localPort;
1440}
1441
1442/*!
1443 Returns the host address of the local socket if available;
1444 otherwise returns QHostAddress::Null.
1445
1446 This is normally the main IP address of the host, but can be
1447 QHostAddress::LocalHost (127.0.0.1) for connections to the
1448 local host.
1449
1450 \sa localPort(), peerAddress(), setLocalAddress()
1451*/
1452QHostAddress QAbstractSocket::localAddress() const
1453{
1454 Q_D(const QAbstractSocket);
1455 return d->localAddress;
1456}
1457
1458/*!
1459 Returns the port of the connected peer if the socket is in
1460 ConnectedState; otherwise returns 0.
1461
1462 \sa peerAddress(), localPort(), setPeerPort()
1463*/
1464quint16 QAbstractSocket::peerPort() const
1465{
1466 Q_D(const QAbstractSocket);
1467 return d->peerPort;
1468}
1469
1470/*!
1471 Returns the address of the connected peer if the socket is in
1472 ConnectedState; otherwise returns QHostAddress::Null.
1473
1474 \sa peerName(), peerPort(), localAddress(), setPeerAddress()
1475*/
1476QHostAddress QAbstractSocket::peerAddress() const
1477{
1478 Q_D(const QAbstractSocket);
1479 return d->peerAddress;
1480}
1481
1482/*!
1483 Returns the name of the peer as specified by connectToHost(), or
1484 an empty QString if connectToHost() has not been called.
1485
1486 \sa peerAddress(), peerPort(), setPeerName()
1487*/
1488QString QAbstractSocket::peerName() const
1489{
1490 Q_D(const QAbstractSocket);
1491 return d->peerName.isEmpty() ? d->hostName : d->peerName;
1492}
1493
1494/*!
1495 Returns true if a line of data can be read from the socket;
1496 otherwise returns false.
1497
1498 \sa readLine()
1499*/
1500bool QAbstractSocket::canReadLine() const
1501{
1502 bool hasLine = d_func()->readBuffer.canReadLine();
1503#if defined (QABSTRACTSOCKET_DEBUG)
1504 qDebug("QAbstractSocket::canReadLine() == %s, buffer size = %d, size = %d", hasLine ? "true" : "false",
1505 d_func()->readBuffer.size(), d_func()->buffer.size());
1506#endif
1507 return hasLine || QIODevice::canReadLine();
1508}
1509
1510/*!
1511 Returns the native socket descriptor of the QAbstractSocket object
1512 if this is available; otherwise returns -1.
1513
1514 If the socket is using QNetworkProxy, the returned descriptor
1515 may not be usable with native socket functions.
1516
1517 The socket descriptor is not available when QAbstractSocket is in
1518 UnconnectedState.
1519
1520 \sa setSocketDescriptor()
1521*/
1522int QAbstractSocket::socketDescriptor() const
1523{
1524 Q_D(const QAbstractSocket);
1525 return d->cachedSocketDescriptor;
1526}
1527
1528/*!
1529 Initializes QAbstractSocket with the native socket descriptor \a
1530 socketDescriptor. Returns true if \a socketDescriptor is accepted
1531 as a valid socket descriptor; otherwise returns false.
1532 The socket is opened in the mode specified by \a openMode, and
1533 enters the socket state specified by \a socketState.
1534
1535 \bold{Note:} It is not possible to initialize two abstract sockets
1536 with the same native socket descriptor.
1537
1538 \sa socketDescriptor()
1539*/
1540bool QAbstractSocket::setSocketDescriptor(int socketDescriptor, SocketState socketState,
1541 OpenMode openMode)
1542{
1543 Q_D(QAbstractSocket);
1544#ifndef QT_NO_OPENSSL
1545 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
1546 return socket->setSocketDescriptor(socketDescriptor, socketState, openMode);
1547#endif
1548
1549 d->resetSocketLayer();
1550 d->socketEngine = QAbstractSocketEngine::createSocketEngine(socketDescriptor, this);
1551 if (!d->socketEngine) {
1552 d->socketError = UnsupportedSocketOperationError;
1553 setErrorString(tr("Operation on socket is not supported"));
1554 return false;
1555 }
1556 bool result = d->socketEngine->initialize(socketDescriptor, socketState);
1557 if (!result) {
1558 d->socketError = d->socketEngine->error();
1559 setErrorString(d->socketEngine->errorString());
1560 return false;
1561 }
1562
1563 if (d->threadData->eventDispatcher)
1564 d->socketEngine->setReceiver(d);
1565
1566 QIODevice::open(openMode);
1567
1568 if (d->state != socketState) {
1569 d->state = socketState;
1570 emit stateChanged(d->state);
1571 }
1572
1573 d->pendingClose = false;
1574 d->socketEngine->setReadNotificationEnabled(true);
1575 d->localPort = d->socketEngine->localPort();
1576 d->peerPort = d->socketEngine->peerPort();
1577 d->localAddress = d->socketEngine->localAddress();
1578 d->peerAddress = d->socketEngine->peerAddress();
1579 d->cachedSocketDescriptor = socketDescriptor;
1580
1581#ifdef Q_OS_LINUX
1582 // ### This is a workaround for certain broken Linux kernels, when using
1583 // QTcpSocket with a Unix domain socket. It was introduced around 2.6.9,
1584 // and fixed at some point after that.
1585 // http://archive.linux-usenet.com/index-t-73300.html
1586 // We can provide a better workaround for this: readFromSocket() can loop
1587 // while reading, but this must happen without triggering an implicit
1588 // close because of reading after the socket has closed.
1589 d->addToBytesAvailable = 4096;
1590#endif
1591
1592 return true;
1593}
1594
1595/*!
1596 \since 4.6
1597 Sets the given \a option to the value described by \a value.
1598
1599 \sa socketOption()
1600*/
1601void QAbstractSocket::setSocketOption(QAbstractSocket::SocketOption option, const QVariant &value)
1602{
1603#ifndef QT_NO_OPENSSL
1604 if (QSslSocket *sslSocket = qobject_cast<QSslSocket*>(this)) {
1605 sslSocket->setSocketOption(option, value);
1606 return;
1607 }
1608#endif
1609
1610 if (!d_func()->socketEngine)
1611 return;
1612
1613 switch (option) {
1614 case LowDelayOption:
1615 d_func()->socketEngine->setOption(QAbstractSocketEngine::LowDelayOption, value.toInt());
1616 break;
1617
1618 case KeepAliveOption:
1619 d_func()->socketEngine->setOption(QAbstractSocketEngine::KeepAliveOption, value.toInt());
1620 break;
1621 }
1622}
1623
1624/*!
1625 \since 4.6
1626 Returns the value of the \a option option.
1627
1628 \sa setSocketOption()
1629*/
1630QVariant QAbstractSocket::socketOption(QAbstractSocket::SocketOption option)
1631{
1632#ifndef QT_NO_OPENSSL
1633 if (QSslSocket *sslSocket = qobject_cast<QSslSocket*>(this)) {
1634 return sslSocket->socketOption(option);
1635 }
1636#endif
1637
1638 if (!d_func()->socketEngine)
1639 return QVariant();
1640
1641 int ret = -1;
1642 switch (option) {
1643 case LowDelayOption:
1644 ret = d_func()->socketEngine->option(QAbstractSocketEngine::LowDelayOption);
1645 break;
1646
1647 case KeepAliveOption:
1648 ret = d_func()->socketEngine->option(QAbstractSocketEngine::KeepAliveOption);
1649 break;
1650 }
1651 if (ret == -1)
1652 return QVariant();
1653 else
1654 return QVariant(ret);
1655}
1656
1657
1658/*
1659 Returns the difference between msecs and elapsed. If msecs is -1,
1660 however, -1 is returned.
1661*/
1662static int qt_timeout_value(int msecs, int elapsed)
1663{
1664 if (msecs == -1)
1665 return -1;
1666
1667 int timeout = msecs - elapsed;
1668 return timeout < 0 ? 0 : timeout;
1669}
1670
1671/*!
1672 Waits until the socket is connected, up to \a msecs
1673 milliseconds. If the connection has been established, this
1674 function returns true; otherwise it returns false. In the case
1675 where it returns false, you can call error() to determine
1676 the cause of the error.
1677
1678 The following example waits up to one second for a connection
1679 to be established:
1680
1681 \snippet doc/src/snippets/code/src_network_socket_qabstractsocket.cpp 0
1682
1683 If msecs is -1, this function will not time out.
1684
1685 Note: This function may wait slightly longer than \a msecs,
1686 depending on the time it takes to complete the host lookup.
1687
1688 \sa connectToHost(), connected()
1689*/
1690bool QAbstractSocket::waitForConnected(int msecs)
1691{
1692 Q_D(QAbstractSocket);
1693#if defined (QABSTRACTSOCKET_DEBUG)
1694 qDebug("QAbstractSocket::waitForConnected(%i)", msecs);
1695#endif
1696
1697 if (state() == ConnectedState) {
1698#if defined (QABSTRACTSOCKET_DEBUG)
1699 qDebug("QAbstractSocket::waitForConnected(%i) already connected", msecs);
1700#endif
1701 return true;
1702 }
1703
1704#ifndef QT_NO_OPENSSL
1705 // Manual polymorphism; this function is not virtual, but has an overload
1706 // in QSslSocket.
1707 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
1708 return socket->waitForConnected(msecs);
1709#endif
1710
1711 bool wasPendingClose = d->pendingClose;
1712 d->pendingClose = false;
1713 QTime stopWatch;
1714 stopWatch.start();
1715
1716 if (d->state == HostLookupState) {
1717#if defined (QABSTRACTSOCKET_DEBUG)
1718 qDebug("QAbstractSocket::waitForConnected(%i) doing host name lookup", msecs);
1719#endif
1720 QHostInfo::abortHostLookup(d->hostLookupId);
1721 d->hostLookupId = -1;
1722 d->_q_startConnecting(QHostInfo::fromName(d->hostName));
1723 }
1724 if (state() == UnconnectedState)
1725 return false;
1726
1727 bool timedOut = true;
1728#if defined (QABSTRACTSOCKET_DEBUG)
1729 int attempt = 1;
1730#endif
1731 while (state() == ConnectingState && (msecs == -1 || stopWatch.elapsed() < msecs)) {
1732 int timeout = qt_timeout_value(msecs, stopWatch.elapsed());
1733 if (msecs != -1 && timeout > QT_CONNECT_TIMEOUT)
1734 timeout = QT_CONNECT_TIMEOUT;
1735#if defined (QABSTRACTSOCKET_DEBUG)
1736 qDebug("QAbstractSocket::waitForConnected(%i) waiting %.2f secs for connection attempt #%i",
1737 msecs, timeout / 1000.0, attempt++);
1738#endif
1739 timedOut = false;
1740
1741 if (d->socketEngine && d->socketEngine->waitForWrite(timeout, &timedOut) && !timedOut) {
1742 d->_q_testConnection();
1743 } else {
1744 d->_q_connectToNextAddress();
1745 }
1746 }
1747
1748 if ((timedOut && state() != ConnectedState) || state() == ConnectingState) {
1749 d->socketError = SocketTimeoutError;
1750 d->state = UnconnectedState;
1751 emit stateChanged(d->state);
1752 d->resetSocketLayer();
1753 setErrorString(tr("Socket operation timed out"));
1754 }
1755
1756#if defined (QABSTRACTSOCKET_DEBUG)
1757 qDebug("QAbstractSocket::waitForConnected(%i) == %s", msecs,
1758 state() == ConnectedState ? "true" : "false");
1759#endif
1760 if (state() != ConnectedState)
1761 return false;
1762 if (wasPendingClose)
1763 disconnectFromHost();
1764 return true;
1765}
1766
1767/*!
1768 This function blocks until new data is available for reading and the
1769 \l{QIODevice::}{readyRead()} signal has been emitted. The function
1770 will timeout after \a msecs milliseconds; the default timeout is
1771 30000 milliseconds.
1772
1773 The function returns true if the readyRead() signal is emitted and
1774 there is new data available for reading; otherwise it returns false
1775 (if an error occurred or the operation timed out).
1776
1777 \sa waitForBytesWritten()
1778*/
1779bool QAbstractSocket::waitForReadyRead(int msecs)
1780{
1781 Q_D(QAbstractSocket);
1782#if defined (QABSTRACTSOCKET_DEBUG)
1783 qDebug("QAbstractSocket::waitForReadyRead(%i)", msecs);
1784#endif
1785
1786 // require calling connectToHost() before waitForReadyRead()
1787 if (state() == UnconnectedState) {
1788 /* If all you have is a QIODevice pointer to an abstractsocket, you cannot check
1789 this, so you cannot avoid this warning. */
1790// qWarning("QAbstractSocket::waitForReadyRead() is not allowed in UnconnectedState");
1791 return false;
1792 }
1793
1794 QTime stopWatch;
1795 stopWatch.start();
1796
1797 // handle a socket in connecting state
1798 if (state() == HostLookupState || state() == ConnectingState) {
1799 if (!waitForConnected(msecs))
1800 return false;
1801 }
1802
1803 Q_ASSERT(d->socketEngine);
1804 forever {
1805 bool readyToRead = false;
1806 bool readyToWrite = false;
1807 if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
1808 qt_timeout_value(msecs, stopWatch.elapsed()))) {
1809 d->socketError = d->socketEngine->error();
1810 setErrorString(d->socketEngine->errorString());
1811#if defined (QABSTRACTSOCKET_DEBUG)
1812 qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
1813 msecs, d->socketError, errorString().toLatin1().constData());
1814#endif
1815 emit error(d->socketError);
1816 if (d->socketError != SocketTimeoutError)
1817 close();
1818 return false;
1819 }
1820
1821 if (readyToRead) {
1822 if (d->canReadNotification())
1823 return true;
1824 }
1825
1826 if (readyToWrite)
1827 d->canWriteNotification();
1828
1829 if (state() != ConnectedState)
1830 return false;
1831 }
1832 return false;
1833}
1834
1835/*! \reimp
1836 */
1837bool QAbstractSocket::waitForBytesWritten(int msecs)
1838{
1839 Q_D(QAbstractSocket);
1840#if defined (QABSTRACTSOCKET_DEBUG)
1841 qDebug("QAbstractSocket::waitForBytesWritten(%i)", msecs);
1842#endif
1843
1844 // require calling connectToHost() before waitForBytesWritten()
1845 if (state() == UnconnectedState) {
1846 qWarning("QAbstractSocket::waitForBytesWritten() is not allowed in UnconnectedState");
1847 return false;
1848 }
1849
1850 if (d->writeBuffer.isEmpty())
1851 return false;
1852
1853 QTime stopWatch;
1854 stopWatch.start();
1855
1856 // handle a socket in connecting state
1857 if (state() == HostLookupState || state() == ConnectingState) {
1858 if (!waitForConnected(msecs))
1859 return false;
1860 }
1861
1862 forever {
1863 bool readyToRead = false;
1864 bool readyToWrite = false;
1865 if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, true, !d->writeBuffer.isEmpty(),
1866 qt_timeout_value(msecs, stopWatch.elapsed()))) {
1867 d->socketError = d->socketEngine->error();
1868 setErrorString(d->socketEngine->errorString());
1869#if defined (QABSTRACTSOCKET_DEBUG)
1870 qDebug("QAbstractSocket::waitForBytesWritten(%i) failed (%i, %s)",
1871 msecs, d->socketError, errorString().toLatin1().constData());
1872#endif
1873 emit error(d->socketError);
1874 if (d->socketError != SocketTimeoutError)
1875 close();
1876 return false;
1877 }
1878
1879 if (readyToRead) {
1880#if defined (QABSTRACTSOCKET_DEBUG)
1881 qDebug("QAbstractSocket::waitForBytesWritten calls canReadNotification");
1882#endif
1883 if(!d->canReadNotification())
1884 return false;
1885 }
1886
1887
1888 if (readyToWrite) {
1889 if (d->canWriteNotification()) {
1890#if defined (QABSTRACTSOCKET_DEBUG)
1891 qDebug("QAbstractSocket::waitForBytesWritten returns true");
1892#endif
1893 return true;
1894 }
1895 }
1896
1897 if (state() != ConnectedState)
1898 return false;
1899 }
1900 return false;
1901}
1902
1903/*!
1904 Waits until the socket has disconnected, up to \a msecs
1905 milliseconds. If the connection has been disconnected, this
1906 function returns true; otherwise it returns false. In the case
1907 where it returns false, you can call error() to determine
1908 the cause of the error.
1909
1910 The following example waits up to one second for a connection
1911 to be closed:
1912
1913 \snippet doc/src/snippets/code/src_network_socket_qabstractsocket.cpp 1
1914
1915 If msecs is -1, this function will not time out.
1916
1917 \sa disconnectFromHost(), close()
1918*/
1919bool QAbstractSocket::waitForDisconnected(int msecs)
1920{
1921 Q_D(QAbstractSocket);
1922#ifndef QT_NO_OPENSSL
1923 // Manual polymorphism; this function is not virtual, but has an overload
1924 // in QSslSocket.
1925 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
1926 return socket->waitForDisconnected(msecs);
1927#endif
1928
1929 // require calling connectToHost() before waitForDisconnected()
1930 if (state() == UnconnectedState) {
1931 qWarning("QAbstractSocket::waitForDisconnected() is not allowed in UnconnectedState");
1932 return false;
1933 }
1934
1935 QTime stopWatch;
1936 stopWatch.start();
1937
1938 // handle a socket in connecting state
1939 if (state() == HostLookupState || state() == ConnectingState) {
1940 if (!waitForConnected(msecs))
1941 return false;
1942 if (state() == UnconnectedState)
1943 return true;
1944 }
1945
1946 forever {
1947 bool readyToRead = false;
1948 bool readyToWrite = false;
1949 if (!d->socketEngine->waitForReadOrWrite(&readyToRead, &readyToWrite, state() == ConnectedState,
1950 !d->writeBuffer.isEmpty(),
1951 qt_timeout_value(msecs, stopWatch.elapsed()))) {
1952 d->socketError = d->socketEngine->error();
1953 setErrorString(d->socketEngine->errorString());
1954#if defined (QABSTRACTSOCKET_DEBUG)
1955 qDebug("QAbstractSocket::waitForReadyRead(%i) failed (%i, %s)",
1956 msecs, d->socketError, errorString().toLatin1().constData());
1957#endif
1958 emit error(d->socketError);
1959 if (d->socketError != SocketTimeoutError)
1960 close();
1961 return false;
1962 }
1963
1964 if (readyToRead)
1965 d->canReadNotification();
1966 if (readyToWrite)
1967 d->canWriteNotification();
1968
1969 if (state() == UnconnectedState)
1970 return true;
1971 }
1972 return false;
1973}
1974
1975/*!
1976 Aborts the current connection and resets the socket. Unlike disconnectFromHost(),
1977 this function immediately closes the socket, discarding any pending data in the
1978 write buffer.
1979
1980 \sa disconnectFromHost(), close()
1981*/
1982void QAbstractSocket::abort()
1983{
1984 Q_D(QAbstractSocket);
1985#if defined (QABSTRACTSOCKET_DEBUG)
1986 qDebug("QAbstractSocket::abort()");
1987#endif
1988 if (d->state == UnconnectedState)
1989 return;
1990#ifndef QT_NO_OPENSSL
1991 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this)) {
1992 socket->abort();
1993 return;
1994 }
1995#endif
1996 if (d->connectTimer) {
1997 d->connectTimer->stop();
1998 delete d->connectTimer;
1999 d->connectTimer = 0;
2000 }
2001
2002 d->writeBuffer.clear();
2003 d->abortCalled = true;
2004 close();
2005}
2006
2007/*! \reimp
2008*/
2009bool QAbstractSocket::isSequential() const
2010{
2011 return true;
2012}
2013
2014/*! \reimp
2015
2016 Returns true if no more data is currently
2017 available for reading; otherwise returns false.
2018
2019 This function is most commonly used when reading data from the
2020 socket in a loop. For example:
2021
2022 \snippet doc/src/snippets/code/src_network_socket_qabstractsocket.cpp 2
2023
2024 \sa bytesAvailable(), readyRead()
2025 */
2026bool QAbstractSocket::atEnd() const
2027{
2028 return QIODevice::atEnd() && (!isOpen() || d_func()->readBuffer.isEmpty());
2029}
2030
2031/*!
2032 This function writes as much as possible from the internal write buffer to
2033 the underlying network socket, without blocking. If any data was written,
2034 this function returns true; otherwise false is returned.
2035
2036 Call this function if you need QAbstractSocket to start sending buffered
2037 data immediately. The number of bytes successfully written depends on the
2038 operating system. In most cases, you do not need to call this function,
2039 because QAbstractSocket will start sending data automatically once control
2040 goes back to the event loop. In the absence of an event loop, call
2041 waitForBytesWritten() instead.
2042
2043 \sa write(), waitForBytesWritten()
2044*/
2045// Note! docs copied to QSslSocket::flush()
2046bool QAbstractSocket::flush()
2047{
2048 Q_D(QAbstractSocket);
2049#ifndef QT_NO_OPENSSL
2050 // Manual polymorphism; flush() isn't virtual, but QSslSocket overloads
2051 // it.
2052 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this))
2053 return socket->flush();
2054#endif
2055 Q_CHECK_SOCKETENGINE(false);
2056 return d->flush();
2057}
2058
2059/*! \reimp
2060*/
2061qint64 QAbstractSocket::readData(char *data, qint64 maxSize)
2062{
2063 Q_D(QAbstractSocket);
2064 if (d->socketEngine && !d->socketEngine->isReadNotificationEnabled() && d->socketEngine->isValid())
2065 d->socketEngine->setReadNotificationEnabled(true);
2066
2067 if (!d->isBuffered) {
2068 if (!d->socketEngine)
2069 return -1; // no socket engine is probably EOF
2070 qint64 readBytes = d->socketEngine->read(data, maxSize);
2071 if (readBytes < 0) {
2072 d->socketError = d->socketEngine->error();
2073 setErrorString(d->socketEngine->errorString());
2074 }
2075 if (!d->socketEngine->isReadNotificationEnabled())
2076 d->socketEngine->setReadNotificationEnabled(true);
2077#if defined (QABSTRACTSOCKET_DEBUG)
2078 qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld",
2079 data, qt_prettyDebug(data, 32, readBytes).data(), maxSize,
2080 readBytes);
2081#endif
2082 return readBytes;
2083 }
2084
2085 if (d->readBuffer.isEmpty())
2086 // if we're still connected, return 0 indicating there may be more data in the future
2087 // if we're not connected, return -1 indicating EOF
2088 return d->state == QAbstractSocket::ConnectedState ? qint64(0) : qint64(-1);
2089
2090 // If readFromSocket() read data, copy it to its destination.
2091 if (maxSize == 1) {
2092 *data = d->readBuffer.getChar();
2093#if defined (QABSTRACTSOCKET_DEBUG)
2094 qDebug("QAbstractSocket::readData(%p '%c (0x%.2x)', 1) == 1",
2095 data, isprint(int(uchar(*data))) ? *data : '?', *data);
2096#endif
2097 return 1;
2098 }
2099
2100 qint64 bytesToRead = qMin(qint64(d->readBuffer.size()), maxSize);
2101 qint64 readSoFar = 0;
2102 while (readSoFar < bytesToRead) {
2103 const char *ptr = d->readBuffer.readPointer();
2104 int bytesToReadFromThisBlock = qMin(int(bytesToRead - readSoFar),
2105 d->readBuffer.nextDataBlockSize());
2106 memcpy(data + readSoFar, ptr, bytesToReadFromThisBlock);
2107 readSoFar += bytesToReadFromThisBlock;
2108 d->readBuffer.free(bytesToReadFromThisBlock);
2109 }
2110
2111#if defined (QABSTRACTSOCKET_DEBUG)
2112 qDebug("QAbstractSocket::readData(%p \"%s\", %lli) == %lld",
2113 data, qt_prettyDebug(data, qMin<qint64>(32, readSoFar), readSoFar).data(),
2114 maxSize, readSoFar);
2115#endif
2116 return readSoFar;
2117}
2118
2119/*! \reimp
2120*/
2121qint64 QAbstractSocket::readLineData(char *data, qint64 maxlen)
2122{
2123 return QIODevice::readLineData(data, maxlen);
2124}
2125
2126/*! \reimp
2127*/
2128qint64 QAbstractSocket::writeData(const char *data, qint64 size)
2129{
2130 Q_D(QAbstractSocket);
2131 if (d->state == QAbstractSocket::UnconnectedState) {
2132 d->socketError = QAbstractSocket::UnknownSocketError;
2133 setErrorString(tr("Socket is not connected"));
2134 return -1;
2135 }
2136
2137 if (!d->isBuffered) {
2138 qint64 written = d->socketEngine->write(data, size);
2139 if (written < 0) {
2140 d->socketError = d->socketEngine->error();
2141 setErrorString(d->socketEngine->errorString());
2142 } else if (!d->writeBuffer.isEmpty()) {
2143 d->socketEngine->setWriteNotificationEnabled(true);
2144 }
2145
2146#if defined (QABSTRACTSOCKET_DEBUG)
2147 qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2148 qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2149 size, written);
2150#endif
2151 if (written >= 0)
2152 emit bytesWritten(written);
2153 return written;
2154 }
2155
2156 char *ptr = d->writeBuffer.reserve(size);
2157 if (size == 1)
2158 *ptr = *data;
2159 else
2160 memcpy(ptr, data, size);
2161
2162 qint64 written = size;
2163
2164 if (d->socketEngine && !d->writeBuffer.isEmpty())
2165 d->socketEngine->setWriteNotificationEnabled(true);
2166
2167#if defined (QABSTRACTSOCKET_DEBUG)
2168 qDebug("QAbstractSocket::writeData(%p \"%s\", %lli) == %lli", data,
2169 qt_prettyDebug(data, qMin((int)size, 32), size).data(),
2170 size, written);
2171#endif
2172 return written;
2173}
2174
2175/*!
2176 \since 4.1
2177
2178 Sets the port on the local side of a connection to \a port.
2179
2180 You can call this function in a subclass of QAbstractSocket to
2181 change the return value of the localPort() function after a
2182 connection has been established. This feature is commonly used by
2183 proxy connections for virtual connection settings.
2184
2185 Note that this function does not bind the local port of the socket
2186 prior to a connection (e.g., QUdpSocket::bind()).
2187
2188 \sa localAddress(), setLocalAddress(), setPeerPort()
2189*/
2190void QAbstractSocket::setLocalPort(quint16 port)
2191{
2192 Q_D(QAbstractSocket);
2193 d->localPort = port;
2194}
2195
2196/*!
2197 \since 4.1
2198
2199 Sets the address on the local side of a connection to
2200 \a address.
2201
2202 You can call this function in a subclass of QAbstractSocket to
2203 change the return value of the localAddress() function after a
2204 connection has been established. This feature is commonly used by
2205 proxy connections for virtual connection settings.
2206
2207 Note that this function does not bind the local address of the socket
2208 prior to a connection (e.g., QUdpSocket::bind()).
2209
2210 \sa localAddress(), setLocalPort(), setPeerAddress()
2211*/
2212void QAbstractSocket::setLocalAddress(const QHostAddress &address)
2213{
2214 Q_D(QAbstractSocket);
2215 d->localAddress = address;
2216}
2217
2218/*!
2219 \since 4.1
2220
2221 Sets the port of the remote side of the connection to
2222 \a port.
2223
2224 You can call this function in a subclass of QAbstractSocket to
2225 change the return value of the peerPort() function after a
2226 connection has been established. This feature is commonly used by
2227 proxy connections for virtual connection settings.
2228
2229 \sa peerPort(), setPeerAddress(), setLocalPort()
2230*/
2231void QAbstractSocket::setPeerPort(quint16 port)
2232{
2233 Q_D(QAbstractSocket);
2234 d->peerPort = port;
2235}
2236
2237/*!
2238 \since 4.1
2239
2240 Sets the address of the remote side of the connection
2241 to \a address.
2242
2243 You can call this function in a subclass of QAbstractSocket to
2244 change the return value of the peerAddress() function after a
2245 connection has been established. This feature is commonly used by
2246 proxy connections for virtual connection settings.
2247
2248 \sa peerAddress(), setPeerPort(), setLocalAddress()
2249*/
2250void QAbstractSocket::setPeerAddress(const QHostAddress &address)
2251{
2252 Q_D(QAbstractSocket);
2253 d->peerAddress = address;
2254}
2255
2256/*!
2257 \since 4.1
2258
2259 Sets the host name of the remote peer to \a name.
2260
2261 You can call this function in a subclass of QAbstractSocket to
2262 change the return value of the peerName() function after a
2263 connection has been established. This feature is commonly used by
2264 proxy connections for virtual connection settings.
2265
2266 \sa peerName()
2267*/
2268void QAbstractSocket::setPeerName(const QString &name)
2269{
2270 Q_D(QAbstractSocket);
2271 d->peerName = name;
2272}
2273
2274/*!
2275 Closes the I/O device for the socket, disconnects the socket's connection with the
2276 host, closes the socket, and resets the name, address, port number and underlying
2277 socket descriptor.
2278
2279 See QIODevice::close() for a description of the actions that occur when an I/O
2280 device is closed.
2281
2282 \sa abort()
2283*/
2284void QAbstractSocket::close()
2285{
2286 Q_D(QAbstractSocket);
2287#if defined(QABSTRACTSOCKET_DEBUG)
2288 qDebug("QAbstractSocket::close()");
2289#endif
2290 QIODevice::close();
2291 if (d->state != UnconnectedState) {
2292 d->closeCalled = true;
2293 disconnectFromHost();
2294 }
2295
2296 d->localPort = 0;
2297 d->peerPort = 0;
2298 d->localAddress.clear();
2299 d->peerAddress.clear();
2300 d->peerName.clear();
2301 d->cachedSocketDescriptor = -1;
2302}
2303
2304/*!
2305 Attempts to close the socket. If there is pending data waiting to
2306 be written, QAbstractSocket will enter ClosingState and wait
2307 until all data has been written. Eventually, it will enter
2308 UnconnectedState and emit the disconnected() signal.
2309
2310 \sa connectToHost()
2311*/
2312void QAbstractSocket::disconnectFromHost()
2313{
2314 QMetaObject::invokeMethod(this, "disconnectFromHostImplementation",
2315 Qt::DirectConnection);
2316}
2317
2318/*!
2319 \since 4.1
2320
2321 Contains the implementation of disconnectFromHost().
2322*/
2323void QAbstractSocket::disconnectFromHostImplementation()
2324{
2325 Q_D(QAbstractSocket);
2326#if defined(QABSTRACTSOCKET_DEBUG)
2327 qDebug("QAbstractSocket::disconnectFromHost()");
2328#endif
2329
2330 if (d->state == UnconnectedState) {
2331#if defined(QABSTRACTSOCKET_DEBUG)
2332 qDebug("QAbstractSocket::disconnectFromHost() was called on an unconnected socket");
2333#endif
2334 return;
2335 }
2336
2337 if (!d->abortCalled && (d->state == ConnectingState || d->state == HostLookupState)) {
2338#if defined(QABSTRACTSOCKET_DEBUG)
2339 qDebug("QAbstractSocket::disconnectFromHost() but we're still connecting");
2340#endif
2341 d->pendingClose = true;
2342 return;
2343 }
2344
2345#ifdef QT3_SUPPORT
2346 emit connectionClosed(); // compat signal
2347#endif
2348
2349 // Disable and delete read notification
2350 if (d->socketEngine)
2351 d->socketEngine->setReadNotificationEnabled(false);
2352
2353 if (d->abortCalled) {
2354#if defined(QABSTRACTSOCKET_DEBUG)
2355 qDebug("QAbstractSocket::disconnectFromHost() aborting immediately");
2356#endif
2357 } else {
2358 // Perhaps emit closing()
2359 if (d->state != ClosingState) {
2360 d->state = ClosingState;
2361#if defined(QABSTRACTSOCKET_DEBUG)
2362 qDebug("QAbstractSocket::disconnectFromHost() emits stateChanged()(ClosingState)");
2363#endif
2364 emit stateChanged(d->state);
2365 } else {
2366#if defined(QABSTRACTSOCKET_DEBUG)
2367 qDebug("QAbstractSocket::disconnectFromHost() return from delayed close");
2368#endif
2369 }
2370
2371 // Wait for pending data to be written.
2372 if (d->socketEngine && d->socketEngine->isValid() && (d->writeBuffer.size() > 0
2373 || d->socketEngine->bytesToWrite() > 0)) {
2374 // hack: when we are waiting for the socket engine to write bytes (only
2375 // possible when using Socks5 or HTTP socket engine), then close
2376 // anyway after 2 seconds. This is to prevent a timeout on Mac, where we
2377 // sometimes just did not get the write notifier from the underlying
2378 // CFSocket and no progress was made.
2379 if (d->writeBuffer.size() == 0 && d->socketEngine->bytesToWrite() > 0) {
2380 if (!d->disconnectTimer) {
2381 d->disconnectTimer = new QTimer(this);
2382 connect(d->disconnectTimer, SIGNAL(timeout()), this,
2383 SLOT(_q_forceDisconnect()), Qt::DirectConnection);
2384 }
2385 if (!d->disconnectTimer->isActive())
2386 d->disconnectTimer->start(2000);
2387 }
2388 d->socketEngine->setWriteNotificationEnabled(true);
2389
2390#if defined(QABSTRACTSOCKET_DEBUG)
2391 qDebug("QAbstractSocket::disconnectFromHost() delaying disconnect");
2392#endif
2393 return;
2394 } else {
2395#if defined(QABSTRACTSOCKET_DEBUG)
2396 qDebug("QAbstractSocket::disconnectFromHost() disconnecting immediately");
2397#endif
2398 }
2399 }
2400
2401 SocketState previousState = d->state;
2402 d->resetSocketLayer();
2403 d->state = UnconnectedState;
2404 emit stateChanged(d->state);
2405 emit readChannelFinished(); // we got an EOF
2406
2407#ifdef QT3_SUPPORT
2408 emit delayedCloseFinished(); // compat signal
2409#endif
2410 // only emit disconnected if we were connected before
2411 if (previousState == ConnectedState || previousState == ClosingState)
2412 emit disconnected();
2413
2414 d->localPort = 0;
2415 d->peerPort = 0;
2416 d->localAddress.clear();
2417 d->peerAddress.clear();
2418
2419#if defined(QABSTRACTSOCKET_DEBUG)
2420 qDebug("QAbstractSocket::disconnectFromHost() disconnected!");
2421#endif
2422
2423 if (d->closeCalled) {
2424#if defined(QABSTRACTSOCKET_DEBUG)
2425 qDebug("QAbstractSocket::disconnectFromHost() closed!");
2426#endif
2427 d->readBuffer.clear();
2428 d->writeBuffer.clear();
2429 QIODevice::close();
2430 }
2431}
2432
2433/*!
2434 Returns the size of the internal read buffer. This limits the
2435 amount of data that the client can receive before you call read()
2436 or readAll().
2437
2438 A read buffer size of 0 (the default) means that the buffer has
2439 no size limit, ensuring that no data is lost.
2440
2441 \sa setReadBufferSize(), read()
2442*/
2443qint64 QAbstractSocket::readBufferSize() const
2444{
2445 return d_func()->readBufferMaxSize;
2446}
2447
2448/*!
2449 Sets the size of QAbstractSocket's internal read buffer to be \a
2450 size bytes.
2451
2452 If the buffer size is limited to a certain size, QAbstractSocket
2453 won't buffer more than this size of data. Exceptionally, a buffer
2454 size of 0 means that the read buffer is unlimited and all
2455 incoming data is buffered. This is the default.
2456
2457 This option is useful if you only read the data at certain points
2458 in time (e.g., in a real-time streaming application) or if you
2459 want to protect your socket against receiving too much data,
2460 which may eventually cause your application to run out of memory.
2461
2462 Only QTcpSocket uses QAbstractSocket's internal buffer; QUdpSocket
2463 does not use any buffering at all, but rather relies on the
2464 implicit buffering provided by the operating system.
2465 Because of this, calling this function on QUdpSocket has no
2466 effect.
2467
2468 \sa readBufferSize(), read()
2469*/
2470void QAbstractSocket::setReadBufferSize(qint64 size)
2471{
2472 Q_D(QAbstractSocket);
2473
2474#ifndef QT_NO_OPENSSL
2475 // Manual polymorphism; setReadBufferSize() isn't virtual, but QSslSocket overloads
2476 // it.
2477 if (QSslSocket *socket = qobject_cast<QSslSocket *>(this)) {
2478 socket->setReadBufferSize(size);
2479 return;
2480 }
2481#endif
2482
2483 if (d->readBufferMaxSize == size)
2484 return;
2485 d->readBufferMaxSize = size;
2486 if (!d->readSocketNotifierCalled && d->socketEngine) {
2487 // ensure that the read notification is enabled if we've now got
2488 // room in the read buffer
2489 // but only if we're not inside canReadNotification -- that will take care on its own
2490 if (size == 0 || d->readBuffer.size() < size)
2491 d->socketEngine->setReadNotificationEnabled(true);
2492 }
2493}
2494
2495/*!
2496 Returns the state of the socket.
2497
2498 \sa error()
2499*/
2500QAbstractSocket::SocketState QAbstractSocket::state() const
2501{
2502 return d_func()->state;
2503}
2504
2505/*!
2506 Sets the state of the socket to \a state.
2507
2508 \sa state()
2509*/
2510void QAbstractSocket::setSocketState(SocketState state)
2511{
2512 d_func()->state = state;
2513}
2514
2515/*!
2516 Returns the socket type (TCP, UDP, or other).
2517
2518 \sa QTcpSocket, QUdpSocket
2519*/
2520QAbstractSocket::SocketType QAbstractSocket::socketType() const
2521{
2522 return d_func()->socketType;
2523}
2524
2525/*!
2526 Returns the type of error that last occurred.
2527
2528 \sa state(), errorString()
2529*/
2530QAbstractSocket::SocketError QAbstractSocket::error() const
2531{
2532 return d_func()->socketError;
2533}
2534
2535/*!
2536 Sets the type of error that last occurred to \a socketError.
2537
2538 \sa setSocketState(), setErrorString()
2539*/
2540void QAbstractSocket::setSocketError(SocketError socketError)
2541{
2542 d_func()->socketError = socketError;
2543}
2544
2545#ifndef QT_NO_NETWORKPROXY
2546/*!
2547 \since 4.1
2548
2549 Sets the explicit network proxy for this socket to \a networkProxy.
2550
2551 To disable the use of a proxy for this socket, use the
2552 QNetworkProxy::NoProxy proxy type:
2553
2554 \snippet doc/src/snippets/code/src_network_socket_qabstractsocket.cpp 3
2555
2556 The default value for the proxy is QNetworkProxy::DefaultProxy,
2557 which means the socket will use the application settings: if a
2558 proxy is set with QNetworkProxy::setApplicationProxy, it will use
2559 that; otherwise, if a factory is set with
2560 QNetworkProxyFactory::setApplicationProxyFactory, it will query
2561 that factory with type QNetworkProxyQuery::TcpSocket.
2562
2563 \sa proxy(), QNetworkProxy, QNetworkProxyFactory::queryProxy()
2564*/
2565void QAbstractSocket::setProxy(const QNetworkProxy &networkProxy)
2566{
2567 Q_D(QAbstractSocket);
2568 d->proxy = networkProxy;
2569}
2570
2571/*!
2572 \since 4.1
2573
2574 Returns the network proxy for this socket.
2575 By default QNetworkProxy::DefaultProxy is used, which means this
2576 socket will query the default proxy settings for the application.
2577
2578 \sa setProxy(), QNetworkProxy, QNetworkProxyFactory
2579*/
2580QNetworkProxy QAbstractSocket::proxy() const
2581{
2582 Q_D(const QAbstractSocket);
2583 return d->proxy;
2584}
2585#endif // QT_NO_NETWORKPROXY
2586
2587#ifdef QT3_SUPPORT
2588/*!
2589 \enum QAbstractSocket::Error
2590 \compat
2591
2592 Use QAbstractSocket::SocketError instead.
2593
2594 \value ErrConnectionRefused Use QAbstractSocket::ConnectionRefusedError instead.
2595 \value ErrHostNotFound Use QAbstractSocket::HostNotFoundError instead.
2596 \value ErrSocketRead Use QAbstractSocket::UnknownSocketError instead.
2597*/
2598
2599/*!
2600 \typedef QAbstractSocket::State
2601 \compat
2602
2603 Use QAbstractSocket::SocketState instead.
2604
2605 \table
2606 \header \o Qt 3 enum value \o Qt 4 enum value
2607 \row \o \c Idle \o \l UnconnectedState
2608 \row \o \c HostLookup \o \l HostLookupState
2609 \row \o \c Connecting \o \l ConnectingState
2610 \row \o \c Connected \o \l ConnectedState
2611 \row \o \c Closing \o \l ClosingState
2612 \row \o \c Connection \o \l ConnectedState
2613 \endtable
2614*/
2615
2616/*!
2617 \fn int QAbstractSocket::socket() const
2618
2619 Use socketDescriptor() instead.
2620*/
2621
2622/*!
2623 \fn void QAbstractSocket::setSocket(int socket)
2624
2625 Use setSocketDescriptor() instead.
2626*/
2627
2628/*!
2629 \fn Q_ULONG QAbstractSocket::waitForMore(int msecs, bool *timeout = 0) const
2630
2631 Use waitForReadyRead() instead.
2632
2633 \oldcode
2634 bool timeout;
2635 Q_ULONG numBytes = socket->waitForMore(30000, &timeout);
2636 \newcode
2637 qint64 numBytes = 0;
2638 if (socket->waitForReadyRead(msecs))
2639 numBytes = socket->bytesAvailable();
2640 bool timeout = (error() == QAbstractSocket::SocketTimeoutError);
2641 \endcode
2642
2643 \sa waitForReadyRead(), bytesAvailable(), error(), SocketTimeoutError
2644*/
2645
2646/*!
2647 \fn void QAbstractSocket::connectionClosed()
2648
2649 Use disconnected() instead.
2650*/
2651
2652/*!
2653 \fn void QAbstractSocket::delayedCloseFinished()
2654
2655 Use disconnected() instead.
2656*/
2657#endif // QT3_SUPPORT
2658
2659#ifndef QT_NO_DEBUG_STREAM
2660Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketError error)
2661{
2662 switch (error) {
2663 case QAbstractSocket::ConnectionRefusedError:
2664 debug << "QAbstractSocket::ConnectionRefusedError";
2665 break;
2666 case QAbstractSocket::RemoteHostClosedError:
2667 debug << "QAbstractSocket::RemoteHostClosedError";
2668 break;
2669 case QAbstractSocket::HostNotFoundError:
2670 debug << "QAbstractSocket::HostNotFoundError";
2671 break;
2672 case QAbstractSocket::SocketAccessError:
2673 debug << "QAbstractSocket::SocketAccessError";
2674 break;
2675 case QAbstractSocket::SocketResourceError:
2676 debug << "QAbstractSocket::SocketResourceError";
2677 break;
2678 case QAbstractSocket::SocketTimeoutError:
2679 debug << "QAbstractSocket::SocketTimeoutError";
2680 break;
2681 case QAbstractSocket::DatagramTooLargeError:
2682 debug << "QAbstractSocket::DatagramTooLargeError";
2683 break;
2684 case QAbstractSocket::NetworkError:
2685 debug << "QAbstractSocket::NetworkError";
2686 break;
2687 case QAbstractSocket::AddressInUseError:
2688 debug << "QAbstractSocket::AddressInUseError";
2689 break;
2690 case QAbstractSocket::SocketAddressNotAvailableError:
2691 debug << "QAbstractSocket::SocketAddressNotAvailableError";
2692 break;
2693 case QAbstractSocket::UnsupportedSocketOperationError:
2694 debug << "QAbstractSocket::UnsupportedSocketOperationError";
2695 break;
2696 case QAbstractSocket::UnfinishedSocketOperationError:
2697 debug << "QAbstractSocket::UnfinishedSocketOperationError";
2698 break;
2699 case QAbstractSocket::ProxyAuthenticationRequiredError:
2700 debug << "QAbstractSocket::ProxyAuthenticationRequiredError";
2701 break;
2702 case QAbstractSocket::UnknownSocketError:
2703 debug << "QAbstractSocket::UnknownSocketError";
2704 break;
2705 case QAbstractSocket::ProxyConnectionRefusedError:
2706 debug << "QAbstractSocket::ProxyConnectionRefusedError";
2707 break;
2708 case QAbstractSocket::ProxyConnectionClosedError:
2709 debug << "QAbstractSocket::ProxyConnectionClosedError";
2710 break;
2711 case QAbstractSocket::ProxyConnectionTimeoutError:
2712 debug << "QAbstractSocket::ProxyConnectionTimeoutError";
2713 break;
2714 case QAbstractSocket::ProxyNotFoundError:
2715 debug << "QAbstractSocket::ProxyNotFoundError";
2716 break;
2717 case QAbstractSocket::ProxyProtocolError:
2718 debug << "QAbstractSocket::ProxyProtocolError";
2719 break;
2720 default:
2721 debug << "QAbstractSocket::SocketError(" << int(error) << ')';
2722 break;
2723 }
2724 return debug;
2725}
2726
2727Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketState state)
2728{
2729 switch (state) {
2730 case QAbstractSocket::UnconnectedState:
2731 debug << "QAbstractSocket::UnconnectedState";
2732 break;
2733 case QAbstractSocket::HostLookupState:
2734 debug << "QAbstractSocket::HostLookupState";
2735 break;
2736 case QAbstractSocket::ConnectingState:
2737 debug << "QAbstractSocket::ConnectingState";
2738 break;
2739 case QAbstractSocket::ConnectedState:
2740 debug << "QAbstractSocket::ConnectedState";
2741 break;
2742 case QAbstractSocket::BoundState:
2743 debug << "QAbstractSocket::BoundState";
2744 break;
2745 case QAbstractSocket::ListeningState:
2746 debug << "QAbstractSocket::ListeningState";
2747 break;
2748 case QAbstractSocket::ClosingState:
2749 debug << "QAbstractSocket::ClosingState";
2750 break;
2751 default:
2752 debug << "QAbstractSocket::SocketState(" << int(state) << ')';
2753 break;
2754 }
2755 return debug;
2756}
2757#endif
2758
2759QT_END_NAMESPACE
2760
2761#include "moc_qabstractsocket.cpp"
Note: See TracBrowser for help on using the repository browser.