0
|
1 |
/****************************************************************************
|
|
2 |
**
|
|
3 |
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
|
|
4 |
** All rights reserved.
|
|
5 |
** Contact: Nokia Corporation (qt-info@nokia.com)
|
|
6 |
**
|
|
7 |
** This file is part of the documentation of the Qt Toolkit.
|
|
8 |
**
|
|
9 |
** $QT_BEGIN_LICENSE:LGPL$
|
|
10 |
** No Commercial Usage
|
|
11 |
** This file contains pre-release code and may not be distributed.
|
|
12 |
** You may use this file in accordance with the terms and conditions
|
|
13 |
** contained in the Technology Preview License Agreement accompanying
|
|
14 |
** this package.
|
|
15 |
**
|
|
16 |
** GNU Lesser General Public License Usage
|
|
17 |
** Alternatively, this file may be used under the terms of the GNU Lesser
|
|
18 |
** General Public License version 2.1 as published by the Free Software
|
|
19 |
** Foundation and appearing in the file LICENSE.LGPL included in the
|
|
20 |
** packaging of this file. Please review the following information to
|
|
21 |
** ensure the GNU Lesser General Public License version 2.1 requirements
|
|
22 |
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
|
|
23 |
**
|
|
24 |
** In addition, as a special exception, Nokia gives you certain additional
|
|
25 |
** rights. These rights are described in the Nokia Qt LGPL Exception
|
|
26 |
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
|
|
27 |
**
|
|
28 |
** If you have questions regarding the use of this file, please contact
|
|
29 |
** Nokia at qt-info@nokia.com.
|
|
30 |
**
|
|
31 |
**
|
|
32 |
**
|
|
33 |
**
|
|
34 |
**
|
|
35 |
**
|
|
36 |
**
|
|
37 |
**
|
|
38 |
** $QT_END_LICENSE$
|
|
39 |
**
|
|
40 |
****************************************************************************/
|
|
41 |
|
|
42 |
/*!
|
|
43 |
\group network
|
|
44 |
\title Network Programming API
|
|
45 |
\brief Classes for Network Programming
|
|
46 |
|
|
47 |
\ingroup groups
|
|
48 |
*/
|
|
49 |
|
|
50 |
/*!
|
|
51 |
\page network-programming.html
|
|
52 |
\title Network Programming
|
|
53 |
\brief An Introduction to Network Programming with Qt
|
|
54 |
|
|
55 |
The QtNetwork module offers classes that allow you to write TCP/IP clients
|
|
56 |
and servers. it offers classes such as QFtp that implement specific
|
|
57 |
application-level protocols, lower-level classes such as QTcpSocket,
|
|
58 |
QTcpServer and QUdpSocket that represent low level network concepts,
|
|
59 |
and high level classes such as QNetworkRequest, QNetworkReply and
|
|
60 |
QNetworkAccessManager to perform network operations using common protocols.
|
|
61 |
|
|
62 |
\tableofcontents
|
|
63 |
|
|
64 |
\section1 Qt's Classes for Network Programming
|
|
65 |
|
|
66 |
The following classes provide support for network programming in Qt.
|
|
67 |
|
|
68 |
\annotatedlist network
|
|
69 |
|
|
70 |
\section1 High Level Network Operations for HTTP and FTP
|
|
71 |
|
|
72 |
The Network Access API is a collection of classes for performing
|
|
73 |
common network operations. The API provides an abstraction layer
|
|
74 |
over the specific operations and protocols used (for example,
|
|
75 |
getting and posting data over HTTP), and only exposes classes,
|
|
76 |
functions, and signals for general or high level concepts.
|
|
77 |
|
|
78 |
Network requests are represented by the QNetworkRequest class,
|
|
79 |
which also acts as a general container for information associated
|
|
80 |
with a request, such as any header information and the encryption
|
|
81 |
used. The URL specified when a request object is constructed
|
|
82 |
determines the protocol used for a request.
|
|
83 |
Currently HTTP, FTP and local file URLs are supported for uploading
|
|
84 |
and downloading.
|
|
85 |
|
|
86 |
The coordination of network operations is performed by the
|
|
87 |
QNetworkAccessManager class. Once a request has been created,
|
|
88 |
this class is used to dispatch it and emit signals to report on
|
|
89 |
its progress. The manager also coordinates the use of
|
|
90 |
\l{QNetworkCookieJar}{cookies} to store data on the client,
|
|
91 |
authentication requests, and the use of proxies.
|
|
92 |
|
|
93 |
Replies to network requests are represented by the QNetworkReply
|
|
94 |
class; these are created by QNetworkAccessManager when a request
|
|
95 |
is dispatched. The signals provided by QNetworkReply can be used
|
|
96 |
to monitor each reply individually, or developers may choose to
|
|
97 |
use the manager's signals for this purpose instead and discard
|
|
98 |
references to replies. Since QNetworkReply is a subclass of
|
|
99 |
QIODevice, replies can be handled synchronously or asynchronously;
|
|
100 |
i.e., as blocking or non-blocking operations.
|
|
101 |
|
|
102 |
Each application or library can create one or more instances of
|
|
103 |
QNetworkAccessManager to handle network communication.
|
|
104 |
|
|
105 |
\section1 Writing FTP Clients with QFtp
|
|
106 |
|
|
107 |
FTP (File Transfer Protocol) is a protocol used almost exclusively
|
|
108 |
for browsing remote directories and for transferring files.
|
|
109 |
|
|
110 |
\image httpstack.png FTP Client and Server
|
|
111 |
|
|
112 |
FTP uses two network connections, one for sending
|
|
113 |
commands and one for transferring data. The
|
|
114 |
FTP protocol has a state and requires the client to send several
|
|
115 |
commands before a file transfer takes place.
|
|
116 |
FTP clients establish a connection
|
|
117 |
and keeps it open throughout the session. In each session, multiple
|
|
118 |
transfers can occur.
|
|
119 |
|
|
120 |
The QFtp class provides client-side support for FTP.
|
|
121 |
It has the following characteristics:
|
|
122 |
\list
|
|
123 |
|
|
124 |
\o \e{Non-blocking behavior.} QFtp is asynchronous.
|
|
125 |
You can schedule a series of commands which are executed later,
|
|
126 |
when control returns to Qt's event loop.
|
|
127 |
|
|
128 |
\o \e{Command IDs.} Each command has a unique ID number that you
|
|
129 |
can use to follow the execution of the command. For example, QFtp
|
|
130 |
emits the \l{QFtp::commandStarted()}{commandStarted()} and
|
|
131 |
\l{QFtp::commandFinished()}{commandFinished()} signal with the
|
|
132 |
command ID for each command that is executed.
|
|
133 |
|
|
134 |
\o \e{Data transfer progress indicators.} QFtp emits signals
|
|
135 |
whenever data is transferred (QFtp::dataTransferProgress(),
|
|
136 |
QNetworkReply::downloadProgress(), and
|
|
137 |
QNetworkReply::uploadProgress()). You could connect these signals
|
|
138 |
to QProgressBar::setProgress() or QProgressDialog::setProgress(),
|
|
139 |
for example.
|
|
140 |
|
|
141 |
\o \e{QIODevice support.} The class supports convenient
|
|
142 |
uploading from and downloading to \l{QIODevice}s, in addition to a
|
|
143 |
QByteArray-based API.
|
|
144 |
|
|
145 |
\endlist
|
|
146 |
|
|
147 |
There are two main ways of using QFtp. The most common
|
|
148 |
approach is to keep track of the command IDs and follow the
|
|
149 |
execution of every command by connecting to the appropriate
|
|
150 |
signals. The other approach is to schedule all commands at once
|
|
151 |
and only connect to the done() signal, which is emitted when all
|
|
152 |
scheduled commands have been executed. The first approach
|
|
153 |
requires more work, but it gives you more control over the
|
|
154 |
execution of individual commands and allows you to initiate new
|
|
155 |
commands based on the result of a previous command. It also
|
|
156 |
enables you to provide detailed feedback to the user.
|
|
157 |
|
|
158 |
The \l{network/ftp}{FTP} example
|
|
159 |
illustrates how to write an FTP client.
|
|
160 |
Writing your own FTP (or HTTP) server is possible using the
|
|
161 |
lower-level classes QTcpSocket and QTcpServer.
|
|
162 |
|
|
163 |
\section1 Using TCP with QTcpSocket and QTcpServer
|
|
164 |
|
|
165 |
TCP (Transmission Control Protocol) is a low-level network
|
|
166 |
protocol used by most Internet protocols, including HTTP and FTP,
|
|
167 |
for data transfer. It is a reliable, stream-oriented,
|
|
168 |
connection-oriented transport protocol. It is particularly well
|
|
169 |
suited to the continuous transmission of data.
|
|
170 |
|
|
171 |
\image tcpstream.png A TCP Stream
|
|
172 |
|
|
173 |
The QTcpSocket class provides an interface for TCP. You can use
|
|
174 |
QTcpSocket to implement standard network protocols such as POP3,
|
|
175 |
SMTP, and NNTP, as well as custom protocols.
|
|
176 |
|
|
177 |
A TCP connection must be established to a remote host and port
|
|
178 |
before any data transfer can begin. Once the connection has been
|
|
179 |
established, the IP address and port of the peer are available
|
|
180 |
through QTcpSocket::peerAddress() and QTcpSocket::peerPort(). At
|
|
181 |
any time, the peer can close the connection, and data transfer
|
|
182 |
will then stop immediately.
|
|
183 |
|
|
184 |
QTcpSocket works asynchronously and emits signals to report status
|
|
185 |
changes and errors, just like QNetworkAccessManager and QFtp. It
|
|
186 |
relies on the event loop to detect incoming data and to
|
|
187 |
automatically flush outgoing data. You can write data to the
|
|
188 |
socket using QTcpSocket::write(), and read data using
|
|
189 |
QTcpSocket::read(). QTcpSocket represents two independent streams
|
|
190 |
of data: one for reading and one for writing.
|
|
191 |
|
|
192 |
Since QTcpSocket inherits QIODevice, you can use it with
|
|
193 |
QTextStream and QDataStream. When reading from a QTcpSocket, you
|
|
194 |
must make sure that enough data is available by calling
|
|
195 |
QTcpSocket::bytesAvailable() beforehand.
|
|
196 |
|
|
197 |
If you need to handle incoming TCP connections (e.g., in a server
|
|
198 |
application), use the QTcpServer class. Call QTcpServer::listen()
|
|
199 |
to set up the server, and connect to the
|
|
200 |
QTcpServer::newConnection() signal, which is emitted once for
|
|
201 |
every client that connects. In your slot, call
|
|
202 |
QTcpServer::nextPendingConnection() to accept the connection and
|
|
203 |
use the returned QTcpSocket to communicate with the client.
|
|
204 |
|
|
205 |
Although most of its functions work asynchronously, it's possible
|
|
206 |
to use QTcpSocket synchronously (i.e., blocking). To get blocking
|
|
207 |
behavior, call QTcpSocket's waitFor...() functions; these suspend
|
|
208 |
the calling thread until a signal has been emitted. For example,
|
|
209 |
after calling the non-blocking QTcpSocket::connectToHost()
|
|
210 |
function, call QTcpSocket::waitForConnected() to block the thread
|
|
211 |
until the \l{QTcpSocket::connected()}{connected()} signal has
|
|
212 |
been emitted.
|
|
213 |
|
|
214 |
Synchronous sockets often lead to code with a simpler flow of
|
|
215 |
control. The main disadvantage of the waitFor...() approach is
|
|
216 |
that events won't be processed while a waitFor...() function is
|
|
217 |
blocking. If used in the GUI thread, this might freeze the
|
|
218 |
application's user interface. For this reason, we recommend that
|
|
219 |
you use synchronous sockets only in non-GUI threads. When used
|
|
220 |
synchronously, QTcpSocket doesn't require an event loop.
|
|
221 |
|
|
222 |
The \l{network/fortuneclient}{Fortune Client} and
|
|
223 |
\l{network/fortuneserver}{Fortune Server} examples show how to use
|
|
224 |
QTcpSocket and QTcpServer to write TCP client-server
|
|
225 |
applications. See also \l{network/blockingfortuneclient}{Blocking
|
|
226 |
Fortune Client} for an example on how to use a synchronous
|
|
227 |
QTcpSocket in a separate thread (without using an event loop),
|
|
228 |
and \l{network/threadedfortuneserver}{Threaded Fortune Server}
|
|
229 |
for an example of a multithreaded TCP server with one thread per
|
|
230 |
active client.
|
|
231 |
|
|
232 |
\section1 Using UDP with QUdpSocket
|
|
233 |
|
|
234 |
UDP (User Datagram Protocol) is a lightweight, unreliable,
|
|
235 |
datagram-oriented, connectionless protocol. It can be used when
|
|
236 |
reliability isn't important. For example, a server that reports
|
|
237 |
the time of day could choose UDP. If a datagram with the time of
|
|
238 |
day is lost, the client can simply make another request.
|
|
239 |
|
|
240 |
\image udppackets.png UDP Packets
|
|
241 |
|
|
242 |
The QUdpSocket class allows you to send and receive UDP
|
|
243 |
datagrams. It inherits QAbstractSocket, and it therefore shares
|
|
244 |
most of QTcpSocket's interface. The main difference is that
|
|
245 |
QUdpSocket transfers data as datagrams instead of as a continuous
|
|
246 |
stream of data. In short, a datagram is a data packet of limited
|
|
247 |
size (normally smaller than 512 bytes), containing the IP address
|
|
248 |
and port of the datagram's sender and receiver in addition to the
|
|
249 |
data being transferred.
|
|
250 |
|
|
251 |
QUdpSocket supports IPv4 broadcasting. Broadcasting is often used
|
|
252 |
to implement network discovery protocols, such as finding which
|
|
253 |
host on the network has the most free hard disk space. One host
|
|
254 |
broadcasts a datagram to the network that all other hosts
|
|
255 |
receive. Each host that receives a request then sends a reply
|
|
256 |
back to the sender with its current amount of free disk space.
|
|
257 |
The originator waits until it has received replies from all
|
|
258 |
hosts, and can then choose the server with most free space to
|
|
259 |
store data. To broadcast a datagram, simply send it to the
|
|
260 |
special address QHostAddress::Broadcast (255.255.255.255), or
|
|
261 |
to your local network's broadcast address.
|
|
262 |
|
|
263 |
QUdpSocket::bind() prepares the socket for accepting incoming
|
|
264 |
datagrams, much like QTcpServer::listen() for TCP servers.
|
|
265 |
Whenever one or more datagrams arrive, QUdpSocket emits the
|
|
266 |
\l{QUdpSocket::readyRead()}{readyRead()} signal. Call
|
|
267 |
QUdpSocket::readDatagram() to read the datagram.
|
|
268 |
|
|
269 |
The \l{network/broadcastsender}{Broadcast Sender} and
|
|
270 |
\l{network/broadcastreceiver}{Broadcast Receiver} examples show
|
|
271 |
how to write a UDP sender and a UDP receiver using Qt.
|
|
272 |
|
|
273 |
\section1 Resolving Host Names using QHostInfo
|
|
274 |
|
|
275 |
Before establishing a network connection, QTcpSocket and
|
|
276 |
QUdpSocket perform a name lookup, translating the host name
|
|
277 |
you're connecting to into an IP address. This operation is
|
|
278 |
usually performed using the DNS (Domain Name Service) protocol.
|
|
279 |
|
|
280 |
QHostInfo provides a static function that lets you perform such a
|
|
281 |
lookup yourself. By calling QHostInfo::lookupHost() with a host
|
|
282 |
name, a QObject pointer, and a slot signature, QHostInfo will
|
|
283 |
perform the name lookup and invoke the given slot when the
|
|
284 |
results are ready. The actual lookup is done in a separate
|
|
285 |
thread, making use of the operating system's own methods for
|
|
286 |
performing name lookups.
|
|
287 |
|
|
288 |
QHostInfo also provides a static function called
|
|
289 |
QHostInfo::fromName() that takes the host name as argument and
|
|
290 |
returns the results. In this case, the name lookup is performed
|
|
291 |
in the same thread as the caller. This overload is useful for
|
|
292 |
non-GUI applications or for doing name lookups in a separate,
|
|
293 |
non-GUI thread. (Calling this function in a GUI thread may cause
|
|
294 |
your user interface to freeze while the function blocks as
|
|
295 |
it performs the lookup.)
|
|
296 |
|
|
297 |
\section1 Support for Network Proxies
|
|
298 |
|
|
299 |
Network communication with Qt can be performed through proxies,
|
|
300 |
which direct or filter network traffic between local and remote
|
|
301 |
connections.
|
|
302 |
|
|
303 |
Individual proxies are represented by the QNetworkProxy class,
|
|
304 |
which is used to describe and configure the connection to a proxy.
|
|
305 |
Proxy types which operate on different levels of network communication
|
|
306 |
are supported, with SOCKS 5 support allowing proxying of network
|
|
307 |
traffic at a low level, and HTTP and FTP proxying working at the
|
|
308 |
protocol level. See QNetworkProxy::ProxyType for more information.
|
|
309 |
|
|
310 |
Proxying can be enabled on a per-socket basis or for all network
|
|
311 |
communication in an application. A newly opened socket can be
|
|
312 |
made to use a proxy by calling its QAbstractSocket::setProxy()
|
|
313 |
function before it is connected. Application-wide proxying can
|
|
314 |
be enabled for all subsequent socket connections through the use
|
|
315 |
of the QNetworkProxy::setApplicationProxy() function.
|
|
316 |
|
|
317 |
Proxy factories are used to create policies for proxy use.
|
|
318 |
QNetworkProxyFactory supplies proxies based on queries for specific
|
|
319 |
proxy types. The queries themselves are encoded in QNetworkProxyQuery
|
|
320 |
objects which enable proxies to be selected based on key criteria,
|
|
321 |
such as the purpose of the proxy (TCP, UDP, TCP server, URL request),
|
|
322 |
local port, remote host and port, and the protocol in use (HTTP, FTP,
|
|
323 |
etc.).
|
|
324 |
|
|
325 |
QNetworkProxyFactory::proxyForQuery() is used to query the factory
|
|
326 |
directly. An application-wide policy for proxying can be implemented
|
|
327 |
by passing a factory to QNetworkProxyFactory::setApplicationProxyFactory()
|
|
328 |
and a custom proxying policy can be created by subclassing
|
|
329 |
QNetworkProxyFactory; see the class documentation for details.
|
|
330 |
*/
|