1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtNetwork module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 //#define QTCPSERVER_DEBUG
46 \brief The QTcpServer class provides a TCP-based server.
52 This class makes it possible to accept incoming TCP connections.
53 You can specify the port or have QTcpServer pick one
54 automatically. You can listen on a specific address or on all the
57 Call listen() to have the server listen for incoming connections.
58 The newConnection() signal is then emitted each time a client
59 connects to the server.
61 Call nextPendingConnection() to accept the pending connection as
62 a connected QTcpSocket. The function returns a pointer to a
63 QTcpSocket in QAbstractSocket::ConnectedState that you can use for
64 communicating with the client.
66 If an error occurs, serverError() returns the type of error, and
67 errorString() can be called to get a human readable description of
70 When listening for connections, the address and port on which the
71 server is listening are available as serverAddress() and
74 Calling close() makes QTcpServer stop listening for incoming
77 Although QTcpServer is mostly designed for use with an event
78 loop, it's possible to use it without one. In that case, you must
79 use waitForNewConnection(), which blocks until either a
80 connection is available or a timeout expires.
82 \sa QTcpSocket, {Fortune Server Example}, {Threaded Fortune Server Example},
83 {Loopback Example}, {Torrent Example}
86 /*! \fn void QTcpServer::newConnection()
88 This signal is emitted every time a new connection is available.
90 \sa hasPendingConnections(), nextPendingConnection()
93 #include "private/qobject_p.h"
94 #include "qalgorithms.h"
95 #include "qhostaddress.h"
98 #include "qabstractsocketengine_p.h"
99 #include "qtcpserver.h"
100 #include "qtcpsocket.h"
101 #include "qnetworkproxy.h"
105 #define Q_CHECK_SOCKETENGINE(returnValue) do { \
106 if (!d->socketEngine) { \
107 return returnValue; \
110 class QTcpServerPrivate : public QObjectPrivate, public QAbstractSocketEngineReceiver
112 Q_DECLARE_PUBLIC(QTcpServer)
115 ~QTcpServerPrivate();
117 QList<QTcpSocket *> pendingConnections;
120 QHostAddress address;
122 QAbstractSocket::SocketState state;
123 QAbstractSocketEngine *socketEngine;
125 QAbstractSocket::SocketError serverSocketError;
126 QString serverSocketErrorString;
130 #ifndef QT_NO_NETWORKPROXY
132 QNetworkProxy resolveProxy(const QHostAddress &address, quint16 port);
135 // from QAbstractSocketEngineReceiver
136 void readNotification();
137 inline void writeNotification() {}
138 inline void exceptionNotification() {}
139 inline void connectionNotification() {}
140 #ifndef QT_NO_NETWORKPROXY
141 inline void proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *) {}
148 QTcpServerPrivate::QTcpServerPrivate()
150 , state(QAbstractSocket::UnconnectedState)
152 , serverSocketError(QAbstractSocket::UnknownSocketError)
159 QTcpServerPrivate::~QTcpServerPrivate()
163 #ifndef QT_NO_NETWORKPROXY
166 Resolve the proxy to its final value.
168 QNetworkProxy QTcpServerPrivate::resolveProxy(const QHostAddress &address, quint16 port)
170 if (address.isLoopback())
171 return QNetworkProxy::NoProxy;
173 QList<QNetworkProxy> proxies;
174 if (proxy.type() != QNetworkProxy::DefaultProxy) {
175 // a non-default proxy was set with setProxy
178 // try the application settings instead
179 QNetworkProxyQuery query(port, QString(), QNetworkProxyQuery::TcpServer);
180 proxies = QNetworkProxyFactory::proxyForQuery(query);
183 // return the first that we can use
184 foreach (const QNetworkProxy &p, proxies) {
185 if (p.capabilities() & QNetworkProxy::ListeningCapability)
190 // DefaultProxy will raise an error
191 return QNetworkProxy(QNetworkProxy::DefaultProxy);
197 void QTcpServerPrivate::readNotification()
201 if (pendingConnections.count() >= maxConnections) {
202 #if defined (QTCPSERVER_DEBUG)
203 qDebug("QTcpServerPrivate::_q_processIncomingConnection() too many connections");
205 if (socketEngine->isReadNotificationEnabled())
206 socketEngine->setReadNotificationEnabled(false);
210 int descriptor = socketEngine->accept();
211 if (descriptor == -1)
213 #if defined (QTCPSERVER_DEBUG)
214 qDebug("QTcpServerPrivate::_q_processIncomingConnection() accepted socket %i", descriptor);
216 q->incomingConnection(descriptor);
218 QPointer<QTcpServer> that = q;
219 emit q->newConnection();
220 if (!that || !q->isListening())
226 Constructs a QTcpServer object.
228 \a parent is passed to the QObject constructor.
230 \sa listen(), setSocketDescriptor()
232 QTcpServer::QTcpServer(QObject *parent)
233 : QObject(*new QTcpServerPrivate, parent)
238 Destroys the QTcpServer object. If the server is listening for
239 connections, the socket is automatically closed.
241 Any client \l{QTcpSocket}s that are still connected must either
242 disconnect or be reparented before the server is deleted.
246 QTcpServer::~QTcpServer()
252 Tells the server to listen for incoming connections on address \a
253 address and port \a port. If \a port is 0, a port is chosen
254 automatically. If \a address is QHostAddress::Any, the server
255 will listen on all network interfaces.
257 Returns true on success; otherwise returns false.
261 bool QTcpServer::listen(const QHostAddress &address, quint16 port)
264 if (d->state == QAbstractSocket::ListeningState) {
265 qWarning("QTcpServer::listen() called when already listening");
269 QAbstractSocket::NetworkLayerProtocol proto = address.protocol();
271 #ifdef QT_NO_NETWORKPROXY
272 static const QNetworkProxy &proxy = *(QNetworkProxy *)0;
274 QNetworkProxy proxy = d->resolveProxy(address, port);
277 delete d->socketEngine;
278 d->socketEngine = QAbstractSocketEngine::createSocketEngine(QAbstractSocket::TcpSocket, proxy, this);
279 if (!d->socketEngine) {
280 d->serverSocketError = QAbstractSocket::UnsupportedSocketOperationError;
281 d->serverSocketErrorString = tr("Operation on socket is not supported");
284 #ifndef QT_NO_BEARERMANAGEMENT
285 //copy network session down to the socket engine (if it has been set)
286 d->socketEngine->setProperty("_q_networksession", property("_q_networksession"));
288 if (!d->socketEngine->initialize(QAbstractSocket::TcpSocket, proto)) {
289 d->serverSocketError = d->socketEngine->error();
290 d->serverSocketErrorString = d->socketEngine->errorString();
294 #if defined(Q_OS_UNIX)
295 // Under Unix, we want to be able to bind to the port, even if a socket on
296 // the same address-port is in TIME_WAIT. Under Windows this is possible
297 // anyway -- furthermore, the meaning of reusable on Windows is different:
298 // it means that you can use the same address-port for multiple listening
300 // Don't abort though if we can't set that option. For example the socks
301 // engine doesn't support that option, but that shouldn't prevent us from
302 // trying to bind/listen.
303 d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
306 if (!d->socketEngine->bind(address, port)) {
307 d->serverSocketError = d->socketEngine->error();
308 d->serverSocketErrorString = d->socketEngine->errorString();
312 if (!d->socketEngine->listen()) {
313 d->serverSocketError = d->socketEngine->error();
314 d->serverSocketErrorString = d->socketEngine->errorString();
318 d->socketEngine->setReceiver(d);
319 d->socketEngine->setReadNotificationEnabled(true);
321 d->state = QAbstractSocket::ListeningState;
322 d->address = d->socketEngine->localAddress();
323 d->port = d->socketEngine->localPort();
325 #if defined (QTCPSERVER_DEBUG)
326 qDebug("QTcpServer::listen(%i, \"%s\") == true (listening on port %i)", port,
327 address.toString().toLatin1().constData(), d->socketEngine->localPort());
333 Returns true if the server is currently listening for incoming
334 connections; otherwise returns false.
338 bool QTcpServer::isListening() const
340 Q_D(const QTcpServer);
341 Q_CHECK_SOCKETENGINE(false);
342 return d->socketEngine->state() == QAbstractSocket::ListeningState;
346 Closes the server. The server will no longer listen for incoming
351 void QTcpServer::close()
355 qDeleteAll(d->pendingConnections);
356 d->pendingConnections.clear();
358 if (d->socketEngine) {
359 d->socketEngine->close();
361 d->socketEngine->deleteLater();
362 } QT_CATCH(const std::bad_alloc &) {
363 // in out of memory situations, the socketEngine
364 // will be deleted in ~QTcpServer (it's a child-object of this)
369 d->state = QAbstractSocket::UnconnectedState;
373 Returns the native socket descriptor the server uses to listen
374 for incoming instructions, or -1 if the server is not listening.
376 If the server is using QNetworkProxy, the returned descriptor may
377 not be usable with native socket functions.
379 \sa setSocketDescriptor(), isListening()
381 qintptr QTcpServer::socketDescriptor() const
383 Q_D(const QTcpServer);
384 Q_CHECK_SOCKETENGINE(-1);
385 return d->socketEngine->socketDescriptor();
389 Sets the socket descriptor this server should use when listening
390 for incoming connections to \a socketDescriptor. Returns true if
391 the socket is set successfully; otherwise returns false.
393 The socket is assumed to be in listening state.
395 \sa socketDescriptor(), isListening()
397 bool QTcpServer::setSocketDescriptor(qintptr socketDescriptor)
401 qWarning("QTcpServer::setSocketDescriptor() called when already listening");
406 delete d->socketEngine;
407 d->socketEngine = QAbstractSocketEngine::createSocketEngine(socketDescriptor, this);
408 if (!d->socketEngine) {
409 d->serverSocketError = QAbstractSocket::UnsupportedSocketOperationError;
410 d->serverSocketErrorString = tr("Operation on socket is not supported");
413 #ifndef QT_NO_BEARERMANAGEMENT
414 //copy network session down to the socket engine (if it has been set)
415 d->socketEngine->setProperty("_q_networksession", property("_q_networksession"));
417 if (!d->socketEngine->initialize(socketDescriptor, QAbstractSocket::ListeningState)) {
418 d->serverSocketError = d->socketEngine->error();
419 d->serverSocketErrorString = d->socketEngine->errorString();
420 #if defined (QTCPSERVER_DEBUG)
421 qDebug("QTcpServer::setSocketDescriptor(%i) failed (%s)", socketDescriptor,
422 d->serverSocketErrorString.toLatin1().constData());
427 d->socketEngine->setReceiver(d);
428 d->socketEngine->setReadNotificationEnabled(true);
430 d->state = d->socketEngine->state();
431 d->address = d->socketEngine->localAddress();
432 d->port = d->socketEngine->localPort();
434 #if defined (QTCPSERVER_DEBUG)
435 qDebug("QTcpServer::setSocketDescriptor(%i) succeeded.", socketDescriptor);
441 Returns the server's port if the server is listening for
442 connections; otherwise returns 0.
444 \sa serverAddress(), listen()
446 quint16 QTcpServer::serverPort() const
448 Q_D(const QTcpServer);
449 Q_CHECK_SOCKETENGINE(0);
450 return d->socketEngine->localPort();
454 Returns the server's address if the server is listening for
455 connections; otherwise returns QHostAddress::Null.
457 \sa serverPort(), listen()
459 QHostAddress QTcpServer::serverAddress() const
461 Q_D(const QTcpServer);
462 Q_CHECK_SOCKETENGINE(QHostAddress(QHostAddress::Null));
463 return d->socketEngine->localAddress();
467 Waits for at most \a msec milliseconds or until an incoming
468 connection is available. Returns true if a connection is
469 available; otherwise returns false. If the operation timed out
470 and \a timedOut is not 0, *\a timedOut will be set to true.
472 This is a blocking function call. Its use is disadvised in a
473 single-threaded GUI application, since the whole application will
474 stop responding until the function returns.
475 waitForNewConnection() is mostly useful when there is no event
478 The non-blocking alternative is to connect to the newConnection()
481 If msec is -1, this function will not time out.
483 \sa hasPendingConnections(), nextPendingConnection()
485 bool QTcpServer::waitForNewConnection(int msec, bool *timedOut)
488 if (d->state != QAbstractSocket::ListeningState)
491 if (!d->socketEngine->waitForRead(msec, timedOut)) {
492 d->serverSocketError = d->socketEngine->error();
493 d->serverSocketErrorString = d->socketEngine->errorString();
497 if (timedOut && *timedOut)
500 d->readNotification();
506 Returns true if the server has a pending connection; otherwise
509 \sa nextPendingConnection(), setMaxPendingConnections()
511 bool QTcpServer::hasPendingConnections() const
513 return !d_func()->pendingConnections.isEmpty();
517 Returns the next pending connection as a connected QTcpSocket
520 The socket is created as a child of the server, which means that
521 it is automatically deleted when the QTcpServer object is
522 destroyed. It is still a good idea to delete the object
523 explicitly when you are done with it, to avoid wasting memory.
525 0 is returned if this function is called when there are no pending
528 \note The returned QTcpSocket object cannot be used from another
529 thread. If you want to use an incoming connection from another thread,
530 you need to override incomingConnection().
532 \sa hasPendingConnections()
534 QTcpSocket *QTcpServer::nextPendingConnection()
537 if (d->pendingConnections.isEmpty())
540 if (!d->socketEngine->isReadNotificationEnabled())
541 d->socketEngine->setReadNotificationEnabled(true);
543 return d->pendingConnections.takeFirst();
547 This virtual function is called by QTcpServer when a new
548 connection is available. The \a socketDescriptor argument is the
549 native socket descriptor for the accepted connection.
551 The base implementation creates a QTcpSocket, sets the socket
552 descriptor and then stores the QTcpSocket in an internal list of
553 pending connections. Finally newConnection() is emitted.
555 Reimplement this function to alter the server's behavior when a
556 connection is available.
558 If this server is using QNetworkProxy then the \a socketDescriptor
559 may not be usable with native socket functions, and should only be
560 used with QTcpSocket::setSocketDescriptor().
562 \note If you want to handle an incoming connection as a new QTcpSocket
563 object in another thread you have to pass the socketDescriptor
564 to the other thread and create the QTcpSocket object there and
565 use its setSocketDescriptor() method.
567 \sa newConnection(), nextPendingConnection(), addPendingConnection()
569 void QTcpServer::incomingConnection(qintptr socketDescriptor)
571 #if defined (QTCPSERVER_DEBUG)
572 qDebug("QTcpServer::incomingConnection(%i)", socketDescriptor);
575 QTcpSocket *socket = new QTcpSocket(this);
576 socket->setSocketDescriptor(socketDescriptor);
577 addPendingConnection(socket);
581 This function is called by QTcpServer::incomingConnection()
582 to add the \a socket to the list of pending incoming connections.
584 \note Don't forget to call this member from reimplemented
585 incomingConnection() if you do not want to break the
586 Pending Connections mechanism.
588 \sa incomingConnection()
591 void QTcpServer::addPendingConnection(QTcpSocket* socket)
593 d_func()->pendingConnections.append(socket);
597 Sets the maximum number of pending accepted connections to \a
598 numConnections. QTcpServer will accept no more than \a
599 numConnections incoming connections before
600 nextPendingConnection() is called. By default, the limit is 30
603 Clients may still able to connect after the server has reached
604 its maximum number of pending connections (i.e., QTcpSocket can
605 still emit the connected() signal). QTcpServer will stop
606 accepting the new connections, but the operating system may
607 still keep them in queue.
609 \sa maxPendingConnections(), hasPendingConnections()
611 void QTcpServer::setMaxPendingConnections(int numConnections)
613 d_func()->maxConnections = numConnections;
617 Returns the maximum number of pending accepted connections. The
620 \sa setMaxPendingConnections(), hasPendingConnections()
622 int QTcpServer::maxPendingConnections() const
624 return d_func()->maxConnections;
628 Returns an error code for the last error that occurred.
632 QAbstractSocket::SocketError QTcpServer::serverError() const
634 return d_func()->serverSocketError;
638 Returns a human readable description of the last error that
643 QString QTcpServer::errorString() const
645 return d_func()->serverSocketErrorString;
648 #ifndef QT_NO_NETWORKPROXY
652 Sets the explicit network proxy for this socket to \a networkProxy.
654 To disable the use of a proxy for this socket, use the
655 QNetworkProxy::NoProxy proxy type:
657 \snippet code/src_network_socket_qtcpserver.cpp 0
659 \sa proxy(), QNetworkProxy
661 void QTcpServer::setProxy(const QNetworkProxy &networkProxy)
664 d->proxy = networkProxy;
670 Returns the network proxy for this socket.
671 By default QNetworkProxy::DefaultProxy is used.
673 \sa setProxy(), QNetworkProxy
675 QNetworkProxy QTcpServer::proxy() const
677 Q_D(const QTcpServer);
680 #endif // QT_NO_NETWORKPROXY
684 #include "moc_qtcpserver.cpp"