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