source: trunk/doc/src/qtnetwork.qdoc@ 5

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

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

File size: 16.9 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 documentation 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/*!
43 \module QtNetwork
44 \title QtNetwork Module
45 \contentspage Qt's Modules
46 \previouspage QtGui
47 \nextpage QtOpenGL
48 \ingroup modules
49
50 \brief The QtNetwork module offers classes that allow you to
51 write TCP/IP clients and servers.
52
53 The network module provides classes to make network programming
54 easier and portable. It offers classes such as QHttp and QFtp that
55 implement specific application-level protocols, lower-level classes
56 such as QTcpSocket, QTcpServer and QUdpSocket that represent low
57 level network concepts, and high level classes such as QNetworkRequest,
58 QNetworkReply and QNetworkAccessManager to perform network operations using common protocols.
59
60 The QtNetwork module is part of the \l{Qt Full Framework Edition} and the
61 \l{Open Source Versions of Qt}.
62
63 Topics:
64
65 \tableofcontents
66
67 \section1 Configuring the Build Process
68
69 Applications that use Qt's networking classes need to
70 be configured to be built against the QtNetwork module.
71 The following declaration in a \c qmake project file ensures that
72 an application is compiled and linked appropriately:
73
74 \snippet doc/src/snippets/code/doc_src_qtnetwork.qdoc 0
75
76 This line is necessary because only the QtCore and QtGui modules
77 are used in the default build process.
78
79 To include the definitions of the module's classes, use the
80 following directive:
81
82 \snippet doc/src/snippets/code/doc_src_qtnetwork.qdoc 1
83
84 \section1 High Level Network Operations
85
86 The Network Access API is a collection of classes for performing
87 common network operations. The API provides an abstraction layer
88 over the specific operations and protocols used (for example,
89 getting and posting data over HTTP), and only exposes classes,
90 functions, and signals for general or high level concepts.
91
92 Network requests are represented by the QNetworkRequest class,
93 which also acts as a general container for information associated
94 with a request, such as any header information and the encryption
95 used. The URL specified when a request object is constructed
96 determines the protocol used for a request.
97
98 The coordination of network operations is performed by the
99 QNetworkAccessManager class. Once a request has been created,
100 this class is used to dispatch it and emit signals to report on
101 its progress. The manager also coordinates the use of
102 \l{QNetworkCookieJar}{cookies} to store data on the client,
103 authentication requests, and the use of proxies.
104
105 Replies to network requests are represented by the QNetworkReply
106 class; these are created by QNetworkAccessManager when a request
107 is dispatched. The signals provided by QNetworkReply can be used
108 to monitor each reply individually, or developers may choose to
109 use the manager's signals for this purpose instead and discard
110 references to replies. Since QNetworkReply is a subclass of
111 QIODevice, replies can be handled synchronously or asynchronously;
112 i.e., as blocking or non-blocking operations.
113
114 Each application or library can create one or more instances of
115 QNetworkAccessManager to handle network communication.
116
117 \section1 Writing HTTP and FTP Clients with QHttp and QFtp
118
119 HTTP (Hypertext Transfer Protocol) is an application-level
120 network protocol used mainly for downloading HTML and XML files,
121 but it is also used as a high-level transport protocol for many
122 other types of data, from images and movies to purchase orders
123 and banking transactions. In contrast, FTP (File Transfer
124 Protocol) is a protocol used almost exclusively for browsing
125 remote directories and for transferring files.
126
127 \image httpstack.png HTTP Client and Server
128
129 HTTP is a simpler protocol than FTP in many ways. It uses only
130 one network connection, while FTP uses two (one for sending
131 commands, and one for transferring data). HTTP is a stateless
132 protocol; requests and responses are always self-contained. The
133 FTP protocol has a state and requires the client to send several
134 commands before a file transfer takes place.
135
136 In practice, HTTP clients often use separate connections for
137 separate requests, whereas FTP clients establish one connection
138 and keep it open throughout the session.
139
140 The QHttp and QFtp classes provide client-side support for HTTP
141 and FTP. Since the two protocols are used to solve the same
142 problems, the QHttp and QFtp classes have many features in
143 common:
144
145 \list
146
147 \o \e{Non-blocking behavior.} QHttp and QFtp are asynchronous.
148 You can schedule a series of commands (also called "requests" for
149 HTTP). The commands are executed later, when control returns to
150 Qt's event loop.
151
152 \o \e{Command IDs.} Each command has a unique ID number that you
153 can use to follow the execution of the command. For example, QFtp
154 emits the \l{QFtp::commandStarted()}{commandStarted()} and
155 \l{QFtp::commandFinished()}{commandFinished()} signal with the
156 command ID for each command that is executed. QHttp has a
157 \l{QHttp::requestStarted()}{requestStarted()} and a
158 \l{QHttp::requestFinished()}{requestFinished()} signal that work
159 the same way.
160
161 \o \e{Data transfer progress indicators.} QHttp and QFtp emit
162 signals whenever data is transferred
163 (QFtp::dataTransferProgress(), QHttp::dataReadProgress(), and
164 QHttp::dataSendProgress()). You could connect these signals to
165 QProgressBar::setProgress() or QProgressDialog::setProgress(),
166 for example.
167
168 \o \e{QIODevice support.} Both classes support convenient
169 uploading from and downloading to \l{QIODevice}s, in addition to a
170 QByteArray-based API.
171
172 \endlist
173
174 There are two main ways of using QHttp and QFtp. The most common
175 approach is to keep track of the command IDs and follow the
176 execution of every command by connecting to the appropriate
177 signals. The other approach is to schedule all commands at once
178 and only connect to the done() signal, which is emitted when all
179 scheduled commands have been executed. The first approach
180 requires more work, but it gives you more control over the
181 execution of individual commands and allows you to initiate new
182 commands based on the result of a previous command. It also
183 enables you to provide detailed feedback to the user.
184
185 The \l{network/http}{HTTP} and \l{network/ftp}{FTP} examples
186 illustrate how to write an HTTP and an FTP client.
187
188 Writing your own HTTP or FTP server is possible using the
189 lower-level classes QTcpSocket and QTcpServer.
190
191 \section1 Using TCP with QTcpSocket and QTcpServer
192
193 TCP (Transmission Control Protocol) is a low-level network
194 protocol used by most Internet protocols, including HTTP and FTP,
195 for data transfer. It is a reliable, stream-oriented,
196 connection-oriented transport protocol. It is particularly well
197 suited to the continuous transmission of data.
198
199 \image tcpstream.png A TCP Stream
200
201 The QTcpSocket class provides an interface for TCP. You can use
202 QTcpSocket to implement standard network protocols such as POP3,
203 SMTP, and NNTP, as well as custom protocols.
204
205 A TCP connection must be established to a remote host and port
206 before any data transfer can begin. Once the connection has been
207 established, the IP address and port of the peer are available
208 through QTcpSocket::peerAddress() and QTcpSocket::peerPort(). At
209 any time, the peer can close the connection, and data transfer
210 will then stop immediately.
211
212 QTcpSocket works asynchronously and emits signals to report status
213 changes and errors, just like QHttp and QFtp. It relies on the
214 event loop to detect incoming data and to automatically flush
215 outgoing data. You can write data to the socket using
216 QTcpSocket::write(), and read data using
217 QTcpSocket::read(). QTcpSocket represents two independent streams
218 of data: one for reading and one for writing.
219
220 Since QTcpSocket inherits QIODevice, you can use it with
221 QTextStream and QDataStream. When reading from a QTcpSocket, you
222 must make sure that enough data is available by calling
223 QTcpSocket::bytesAvailable() beforehand.
224
225 If you need to handle incoming TCP connections (e.g., in a server
226 application), use the QTcpServer class. Call QTcpServer::listen()
227 to set up the server, and connect to the
228 QTcpServer::newConnection() signal, which is emitted once for
229 every client that connects. In your slot, call
230 QTcpServer::nextPendingConnection() to accept the connection and
231 use the returned QTcpSocket to communicate with the client.
232
233 Although most of its functions work asynchronously, it's possible
234 to use QTcpSocket synchronously (i.e., blocking). To get blocking
235 behavior, call QTcpSocket's waitFor...() functions; these suspend
236 the calling thread until a signal has been emitted. For example,
237 after calling the non-blocking QTcpSocket::connectToHost()
238 function, call QTcpSocket::waitForConnected() to block the thread
239 until the \l{QTcpSocket::connected()}{connected()} signal has
240 been emitted.
241
242 Synchronous sockets often lead to code with a simpler flow of
243 control. The main disadvantage of the waitFor...() approach is
244 that events won't be processed while a waitFor...() function is
245 blocking. If used in the GUI thread, this might freeze the
246 application's user interface. For this reason, we recommend that
247 you use synchronous sockets only in non-GUI threads. When used
248 synchronously, QTcpSocket doesn't require an event loop.
249
250 The \l{network/fortuneclient}{Fortune Client} and
251 \l{network/fortuneserver}{Fortune Server} examples show how to use
252 QTcpSocket and QTcpServer to write TCP client-server
253 applications. See also \l{network/blockingfortuneclient}{Blocking
254 Fortune Client} for an example on how to use a synchronous
255 QTcpSocket in a separate thread (without using an event loop),
256 and \l{network/threadedfortuneserver}{Threaded Fortune Server}
257 for an example of a multithreaded TCP server with one thread per
258 active client.
259
260 \section1 Using UDP with QUdpSocket
261
262 UDP (User Datagram Protocol) is a lightweight, unreliable,
263 datagram-oriented, connectionless protocol. It can be used when
264 reliability isn't important. For example, a server that reports
265 the time of day could choose UDP. If a datagram with the time of
266 day is lost, the client can simply make another request.
267
268 \image udppackets.png UDP Packets
269
270 The QUdpSocket class allows you to send and receive UDP
271 datagrams. It inherits QAbstractSocket, and it therefore shares
272 most of QTcpSocket's interface. The main difference is that
273 QUdpSocket transfers data as datagrams instead of as a continuous
274 stream of data. In short, a datagram is a data packet of limited
275 size (normally smaller than 512 bytes), containing the IP address
276 and port of the datagram's sender and receiver in addition to the
277 data being transferred.
278
279 QUdpSocket supports IPv4 broadcasting. Broadcasting is often used
280 to implement network discovery protocols, such as finding which
281 host on the network has the most free hard disk space. One host
282 broadcasts a datagram to the network that all other hosts
283 receive. Each host that receives a request then sends a reply
284 back to the sender with its current amount of free disk space.
285 The originator waits until it has received replies from all
286 hosts, and can then choose the server with most free space to
287 store data. To broadcast a datagram, simply send it to the
288 special address QHostAddress::Broadcast (255.255.255.255), or
289 to your local network's broadcast address.
290
291 QUdpSocket::bind() prepares the socket for accepting incoming
292 datagrams, much like QTcpServer::listen() for TCP servers.
293 Whenever one or more datagrams arrive, QUdpSocket emits the
294 \l{QUdpSocket::readyRead()}{readyRead()} signal. Call
295 QUdpSocket::readDatagram() to read the datagram.
296
297 The \l{network/broadcastsender}{Broadcast Sender} and
298 \l{network/broadcastreceiver}{Broadcast Receiver} examples show
299 how to write a UDP sender and a UDP receiver using Qt.
300
301 \section1 Resolving Host Names using QHostInfo
302
303 Before establishing a network connection, QTcpSocket and
304 QUdpSocket perform a name lookup, translating the host name
305 you're connecting to into an IP address. This operation is
306 usually performed using the DNS (Domain Name Service) protocol.
307
308 QHostInfo provides a static function that lets you perform such a
309 lookup yourself. By calling QHostInfo::lookupHost() with a host
310 name, a QObject pointer, and a slot signature, QHostInfo will
311 perform the name lookup and invoke the given slot when the
312 results are ready. The actual lookup is done in a separate
313 thread, making use of the operating system's own methods for
314 performing name lookups.
315
316 QHostInfo also provides a static function called
317 QHostInfo::fromName() that takes the host name as argument and
318 returns the results. In this case, the name lookup is performed
319 in the same thread as the caller. This overload is useful for
320 non-GUI applications or for doing name lookups in a separate,
321 non-GUI thread. (Calling this function in a GUI thread may cause
322 your user interface to freeze while the function blocks as
323 it performs the lookup.)
324
325 \section1 Support for Network Proxies
326
327 Network communication with Qt can be performed through proxies,
328 which direct or filter network traffic between local and remote
329 connections.
330
331 Individual proxies are represented by the QNetworkProxy class,
332 which is used to describe and configure the connection to a proxy.
333 Proxy types which operate on different levels of network communication
334 are supported, with SOCKS 5 support allowing proxying of network
335 traffic at a low level, and HTTP and FTP proxying working at the
336 protocol level. See QNetworkProxy::ProxyType for more information.
337
338 Proxying can be enabled on a per-socket basis or for all network
339 communication in an application. A newly opened socket can be
340 made to use a proxy by calling its QAbstractSocket::setProxy()
341 function before it is connected. Application-wide proxying can
342 be enabled for all subsequent socket connections through the use
343 of the QNetworkProxy::setApplicationProxy() function.
344
345 Proxy factories are used to create policies for proxy use.
346 QNetworkProxyFactory supplies proxies based on queries for specific
347 proxy types. The queries themselves are encoded in QNetworkProxyQuery
348 objects which enable proxies to be selected based on key criteria,
349 such as the purpose of the proxy (TCP, UDP, TCP server, URL request),
350 local port, remote host and port, and the protocol in use (HTTP, FTP,
351 etc.).
352
353 QNetworkProxyFactory::proxyForQuery() is used to query the factory
354 directly. An application-wide policy for proxying can be implemented
355 by passing a factory to QNetworkProxyFactory::setApplicationProxyFactory()
356 and a custom proxying policy can be created by subclassing
357 QNetworkProxyFactory; see the class documentation for details.
358*/
Note: See TracBrowser for help on using the repository browser.