source: trunk/src/network/socket/qtcpserver.cpp@ 159

Last change on this file since 159 was 2, checked in by Dmitry A. Kuminov, 17 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

File size: 18.8 KB
Line 
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 QTCPSERVER_DEBUG
43
44/*! \class QTcpServer
45
46 \brief The QTcpServer class provides a TCP-based server.
47
48 \reentrant
49 \ingroup io
50 \inmodule QtNetwork
51
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
55 machine's addresses.
56
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.
60
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.
65
66 If an error occurs, serverError() returns the type of error, and
67 errorString() can be called to get a human readable description of
68 what happened.
69
70 When listening for connections, the address and port on which the
71 server is listening are available as serverAddress() and
72 serverPort().
73
74 Calling close() makes QTcpServer stop listening for incoming
75 connections.
76
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.
81
82 \sa QTcpSocket, {Fortune Server Example}, {Threaded Fortune Server Example},
83 {Loopback Example}, {Torrent Example}
84*/
85
86/*! \fn void QTcpServer::newConnection()
87
88 This signal is emitted every time a new connection is available.
89
90 \sa hasPendingConnections(), nextPendingConnection()
91*/
92
93#include "private/qobject_p.h"
94#include "qalgorithms.h"
95#include "qhostaddress.h"
96#include "qlist.h"
97#include "qpointer.h"
98#include "qnativesocketengine_p.h"
99#include "qtcpserver.h"
100#include "qtcpsocket.h"
101#include "qnetworkproxy.h"
102
103QT_BEGIN_NAMESPACE
104
105#define Q_CHECK_SOCKETENGINE(returnValue) do { \
106 if (!d->socketEngine) { \
107 return returnValue; \
108 } } while (0)
109
110class QTcpServerPrivate : public QObjectPrivate, public QAbstractSocketEngineReceiver
111{
112 Q_DECLARE_PUBLIC(QTcpServer)
113public:
114 QTcpServerPrivate();
115 ~QTcpServerPrivate();
116
117 QList<QTcpSocket *> pendingConnections;
118
119 quint16 port;
120 QHostAddress address;
121
122 QAbstractSocket::SocketState state;
123 QAbstractSocketEngine *socketEngine;
124
125 QAbstractSocket::SocketError serverSocketError;
126 QString serverSocketErrorString;
127
128 int maxConnections;
129
130#ifndef QT_NO_NETWORKPROXY
131 QNetworkProxy proxy;
132 QNetworkProxy resolveProxy(const QHostAddress &address, quint16 port);
133#endif
134
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 *) {}
142#endif
143
144};
145
146/*! \internal
147*/
148QTcpServerPrivate::QTcpServerPrivate()
149 : port(0)
150 , state(QAbstractSocket::UnconnectedState)
151 , socketEngine(0)
152 , serverSocketError(QAbstractSocket::UnknownSocketError)
153 , maxConnections(30)
154{
155}
156
157/*! \internal
158*/
159QTcpServerPrivate::~QTcpServerPrivate()
160{
161}
162
163#ifndef QT_NO_NETWORKPROXY
164/*! \internal
165
166 Resolve the proxy to its final value.
167*/
168QNetworkProxy QTcpServerPrivate::resolveProxy(const QHostAddress &address, quint16 port)
169{
170 if (address == QHostAddress::LocalHost ||
171 address == QHostAddress::LocalHostIPv6)
172 return QNetworkProxy::NoProxy;
173
174 QList<QNetworkProxy> proxies;
175 if (proxy.type() != QNetworkProxy::DefaultProxy) {
176 // a non-default proxy was set with setProxy
177 proxies << proxy;
178 } else {
179 // try the application settings instead
180 QNetworkProxyQuery query(port, QString(), QNetworkProxyQuery::TcpServer);
181 proxies = QNetworkProxyFactory::proxyForQuery(query);
182 }
183
184 // return the first that we can use
185 foreach (const QNetworkProxy &p, proxies) {
186 if (p.capabilities() & QNetworkProxy::ListeningCapability)
187 return p;
188 }
189
190 // no proxy found
191 // DefaultProxy will raise an error
192 return QNetworkProxy(QNetworkProxy::DefaultProxy);
193}
194#endif
195
196/*! \internal
197*/
198void QTcpServerPrivate::readNotification()
199{
200 Q_Q(QTcpServer);
201 for (;;) {
202 if (pendingConnections.count() >= maxConnections) {
203#if defined (QTCPSERVER_DEBUG)
204 qDebug("QTcpServerPrivate::_q_processIncomingConnection() too many connections");
205#endif
206 if (socketEngine->isReadNotificationEnabled())
207 socketEngine->setReadNotificationEnabled(false);
208 return;
209 }
210
211 int descriptor = socketEngine->accept();
212 if (descriptor == -1)
213 break;
214#if defined (QTCPSERVER_DEBUG)
215 qDebug("QTcpServerPrivate::_q_processIncomingConnection() accepted socket %i", descriptor);
216#endif
217 q->incomingConnection(descriptor);
218
219 QPointer<QTcpServer> that = q;
220 emit q->newConnection();
221 if (!that || !q->isListening())
222 return;
223 }
224}
225
226/*!
227 Constructs a QTcpServer object.
228
229 \a parent is passed to the QObject constructor.
230
231 \sa listen(), setSocketDescriptor()
232*/
233QTcpServer::QTcpServer(QObject *parent)
234 : QObject(*new QTcpServerPrivate, parent)
235{
236}
237
238/*!
239 Destroys the QTcpServer object. If the server is listening for
240 connections, the socket is automatically closed.
241
242 Any client \l{QTcpSocket}s that are still connected must either
243 disconnect or be reparented before the server is deleted.
244
245 \sa close()
246*/
247QTcpServer::~QTcpServer()
248{
249 close();
250}
251
252/*!
253 Tells the server to listen for incoming connections on address \a
254 address and port \a port. If \a port is 0, a port is chosen
255 automatically. If \a address is QHostAddress::Any, the server
256 will listen on all network interfaces.
257
258 Returns true on success; otherwise returns false.
259
260 \sa isListening()
261*/
262bool QTcpServer::listen(const QHostAddress &address, quint16 port)
263{
264 Q_D(QTcpServer);
265 if (d->state == QAbstractSocket::ListeningState) {
266 qWarning("QTcpServer::listen() called when already listening");
267 return false;
268 }
269
270 QAbstractSocket::NetworkLayerProtocol proto = address.protocol();
271
272#ifdef QT_NO_NETWORKPROXY
273 static const QNetworkProxy &proxy = *(QNetworkProxy *)0;
274#else
275 QNetworkProxy proxy = d->resolveProxy(address, port);
276#endif
277
278 delete d->socketEngine;
279 d->socketEngine = QAbstractSocketEngine::createSocketEngine(QAbstractSocket::TcpSocket, proxy, this);
280 if (!d->socketEngine) {
281 d->serverSocketError = QAbstractSocket::UnsupportedSocketOperationError;
282 d->serverSocketErrorString = tr("Operation on socket is not supported");
283 return false;
284 }
285 if (!d->socketEngine->initialize(QAbstractSocket::TcpSocket, proto)) {
286 d->serverSocketError = d->socketEngine->error();
287 d->serverSocketErrorString = d->socketEngine->errorString();
288 return false;
289 }
290
291#if defined(Q_OS_UNIX)
292 // Under Unix, we want to be able to bind to the port, even if a socket on
293 // the same address-port is in TIME_WAIT. Under Windows this is possible
294 // anyway -- furthermore, the meaning of reusable on Windows is different:
295 // it means that you can use the same address-port for multiple listening
296 // sockets.
297 // Don't abort though if we can't set that option. For example the socks
298 // engine doesn't support that option, but that shouldn't prevent us from
299 // trying to bind/listen.
300 d->socketEngine->setOption(QAbstractSocketEngine::AddressReusable, 1);
301#endif
302
303 if (!d->socketEngine->bind(address, port)) {
304 d->serverSocketError = d->socketEngine->error();
305 d->serverSocketErrorString = d->socketEngine->errorString();
306 return false;
307 }
308
309 if (!d->socketEngine->listen()) {
310 d->serverSocketError = d->socketEngine->error();
311 d->serverSocketErrorString = d->socketEngine->errorString();
312 return false;
313 }
314
315 d->socketEngine->setReceiver(d);
316 d->socketEngine->setReadNotificationEnabled(true);
317
318 d->state = QAbstractSocket::ListeningState;
319 d->address = d->socketEngine->localAddress();
320 d->port = d->socketEngine->localPort();
321
322#if defined (QTCPSERVER_DEBUG)
323 qDebug("QTcpServer::listen(%i, \"%s\") == true (listening on port %i)", port,
324 address.toString().toLatin1().constData(), d->socketEngine->localPort());
325#endif
326 return true;
327}
328
329/*!
330 Returns true if the server is currently listening for incoming
331 connections; otherwise returns false.
332
333 \sa listen()
334*/
335bool QTcpServer::isListening() const
336{
337 Q_D(const QTcpServer);
338 Q_CHECK_SOCKETENGINE(false);
339 return d->socketEngine->state() == QAbstractSocket::ListeningState;
340}
341
342/*!
343 Closes the server. The server will no longer listen for incoming
344 connections.
345
346 \sa listen()
347*/
348void QTcpServer::close()
349{
350 Q_D(QTcpServer);
351
352 qDeleteAll(d->pendingConnections);
353 d->pendingConnections.clear();
354
355 if (d->socketEngine) {
356 d->socketEngine->close();
357 d->socketEngine->deleteLater();
358 d->socketEngine = 0;
359 }
360
361 d->state = QAbstractSocket::UnconnectedState;
362}
363
364/*!
365 Returns the native socket descriptor the server uses to listen
366 for incoming instructions, or -1 if the server is not listening.
367
368 If the server is using QNetworkProxy, the returned descriptor may
369 not be usable with native socket functions.
370
371 \sa setSocketDescriptor(), isListening()
372*/
373int QTcpServer::socketDescriptor() const
374{
375 Q_D(const QTcpServer);
376 Q_CHECK_SOCKETENGINE(-1);
377 return d->socketEngine->socketDescriptor();
378}
379
380/*!
381 Sets the socket descriptor this server should use when listening
382 for incoming connections to \a socketDescriptor. Returns true if
383 the socket is set successfully; otherwise returns false.
384
385 The socket is assumed to be in listening state.
386
387 \sa socketDescriptor(), isListening()
388*/
389bool QTcpServer::setSocketDescriptor(int socketDescriptor)
390{
391 Q_D(QTcpServer);
392 if (isListening()) {
393 qWarning("QTcpServer::setSocketDescriptor() called when already listening");
394 return false;
395 }
396
397 if (d->socketEngine)
398 delete d->socketEngine;
399 d->socketEngine = QAbstractSocketEngine::createSocketEngine(socketDescriptor, this);
400 if (!d->socketEngine->initialize(socketDescriptor, QAbstractSocket::ListeningState)) {
401 d->serverSocketError = d->socketEngine->error();
402 d->serverSocketErrorString = d->socketEngine->errorString();
403#if defined (QTCPSERVER_DEBUG)
404 qDebug("QTcpServer::setSocketDescriptor(%i) failed (%s)", socketDescriptor,
405 d->serverSocketErrorString.toLatin1().constData());
406#endif
407 return false;
408 }
409
410 d->socketEngine->setReceiver(d);
411 d->socketEngine->setReadNotificationEnabled(true);
412
413 d->state = d->socketEngine->state();
414 d->address = d->socketEngine->localAddress();
415 d->port = d->socketEngine->localPort();
416
417#if defined (QTCPSERVER_DEBUG)
418 qDebug("QTcpServer::setSocketDescriptor(%i) succeeded.", socketDescriptor);
419#endif
420 return true;
421}
422
423/*!
424 Returns the server's port if the server is listening for
425 connections; otherwise returns 0.
426
427 \sa serverAddress(), listen()
428*/
429quint16 QTcpServer::serverPort() const
430{
431 Q_D(const QTcpServer);
432 Q_CHECK_SOCKETENGINE(0);
433 return d->socketEngine->localPort();
434}
435
436/*!
437 Returns the server's address if the server is listening for
438 connections; otherwise returns QHostAddress::Null.
439
440 \sa serverPort(), listen()
441*/
442QHostAddress QTcpServer::serverAddress() const
443{
444 Q_D(const QTcpServer);
445 Q_CHECK_SOCKETENGINE(QHostAddress(QHostAddress::Null));
446 return d->socketEngine->localAddress();
447}
448
449/*!
450 Waits for at most \a msec milliseconds or until an incoming
451 connection is available. Returns true if a connection is
452 available; otherwise returns false. If the operation timed out
453 and \a timedOut is not 0, *\a timedOut will be set to true.
454
455 This is a blocking function call. Its use is disadvised in a
456 single-threaded GUI application, since the whole application will
457 stop responding until the function returns.
458 waitForNewConnection() is mostly useful when there is no event
459 loop available.
460
461 The non-blocking alternative is to connect to the newConnection()
462 signal.
463
464 If msec is -1, this function will not time out.
465
466 \sa hasPendingConnections(), nextPendingConnection()
467*/
468bool QTcpServer::waitForNewConnection(int msec, bool *timedOut)
469{
470 Q_D(QTcpServer);
471 if (d->state != QAbstractSocket::ListeningState)
472 return false;
473
474 if (!d->socketEngine->waitForRead(msec, timedOut)) {
475 d->serverSocketError = d->socketEngine->error();
476 d->serverSocketErrorString = d->socketEngine->errorString();
477 return false;
478 }
479
480 if (timedOut && *timedOut)
481 return false;
482
483 d->readNotification();
484
485 return true;
486}
487
488/*!
489 Returns true if the server has a pending connection; otherwise
490 returns false.
491
492 \sa nextPendingConnection(), setMaxPendingConnections()
493*/
494bool QTcpServer::hasPendingConnections() const
495{
496 return !d_func()->pendingConnections.isEmpty();
497}
498
499/*!
500 Returns the next pending connection as a connected QTcpSocket
501 object.
502
503 The socket is created as a child of the server, which means that
504 it is automatically deleted when the QTcpServer object is
505 destroyed. It is still a good idea to delete the object
506 explicitly when you are done with it, to avoid wasting memory.
507
508 0 is returned if this function is called when there are no pending
509 connections.
510
511 \sa hasPendingConnections()
512*/
513QTcpSocket *QTcpServer::nextPendingConnection()
514{
515 Q_D(QTcpServer);
516 if (d->pendingConnections.isEmpty())
517 return 0;
518
519 if (!d->socketEngine->isReadNotificationEnabled())
520 d->socketEngine->setReadNotificationEnabled(true);
521
522 return d->pendingConnections.takeFirst();
523}
524
525/*!
526 This virtual function is called by QTcpServer when a new
527 connection is available. The \a socketDescriptor argument is the
528 native socket descriptor for the accepted connection.
529
530 The base implementation creates a QTcpSocket, sets the socket
531 descriptor and then stores the QTcpSocket in an internal list of
532 pending connections. Finally newConnection() is emitted.
533
534 Reimplement this function to alter the server's behavior when a
535 connection is available.
536
537 If this server is using QNetworkProxy then the \a socketDescriptor
538 may not be usable with native socket functions, and should only be
539 used with QTcpSocket::setSocketDescriptor().
540
541 \sa newConnection(), nextPendingConnection()
542*/
543void QTcpServer::incomingConnection(int socketDescriptor)
544{
545#if defined (QTCPSERVER_DEBUG)
546 qDebug("QTcpServer::incomingConnection(%i)", socketDescriptor);
547#endif
548
549 QTcpSocket *socket = new QTcpSocket(this);
550 socket->setSocketDescriptor(socketDescriptor);
551 d_func()->pendingConnections.append(socket);
552}
553
554/*!
555 Sets the maximum number of pending accepted connections to \a
556 numConnections. QTcpServer will accept no more than \a
557 numConnections incoming connections before
558 nextPendingConnection() is called. By default, the limit is 30
559 pending connections.
560
561 Clients may still able to connect after the server has reached
562 its maximum number of pending connections (i.e., QTcpSocket can
563 still emit the connected() signal). QTcpServer will stop
564 accepting the new connections, but the operating system may
565 still keep them in queue.
566
567 \sa maxPendingConnections(), hasPendingConnections()
568*/
569void QTcpServer::setMaxPendingConnections(int numConnections)
570{
571 d_func()->maxConnections = numConnections;
572}
573
574/*!
575 Returns the maximum number of pending accepted connections. The
576 default is 30.
577
578 \sa setMaxPendingConnections(), hasPendingConnections()
579*/
580int QTcpServer::maxPendingConnections() const
581{
582 return d_func()->maxConnections;
583}
584
585/*!
586 Returns an error code for the last error that occurred.
587
588 \sa errorString()
589*/
590QAbstractSocket::SocketError QTcpServer::serverError() const
591{
592 return d_func()->serverSocketError;
593}
594
595/*!
596 Returns a human readable description of the last error that
597 occurred.
598
599 \sa serverError()
600*/
601QString QTcpServer::errorString() const
602{
603 return d_func()->serverSocketErrorString;
604}
605
606#ifndef QT_NO_NETWORKPROXY
607/*!
608 \since 4.1
609
610 Sets the explicit network proxy for this socket to \a networkProxy.
611
612 To disable the use of a proxy for this socket, use the
613 QNetworkProxy::NoProxy proxy type:
614
615 \snippet doc/src/snippets/code/src_network_socket_qtcpserver.cpp 0
616
617 \sa proxy(), QNetworkProxy
618*/
619void QTcpServer::setProxy(const QNetworkProxy &networkProxy)
620{
621 Q_D(QTcpServer);
622 d->proxy = networkProxy;
623}
624
625/*!
626 \since 4.1
627
628 Returns the network proxy for this socket.
629 By default QNetworkProxy::DefaultProxy is used.
630
631 \sa setProxy(), QNetworkProxy
632*/
633QNetworkProxy QTcpServer::proxy() const
634{
635 Q_D(const QTcpServer);
636 return d->proxy;
637}
638#endif // QT_NO_NETWORKPROXY
639
640QT_END_NAMESPACE
641
642#include "moc_qtcpserver.cpp"
643
Note: See TracBrowser for help on using the repository browser.