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 documentation of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:FDL$
9 ** GNU Free Documentation License
10 ** Alternatively, this file may be used under the terms of the GNU Free
11 ** Documentation License version 1.3 as published by the Free Software
12 ** Foundation and appearing in the file included in the packaging of
16 ** Alternatively, this file may be used in accordance with the terms
17 ** and conditions contained in a signed written agreement between you
26 ****************************************************************************/
30 \title Network Programming API
31 \brief Classes for Network Programming
37 \page qtnetwork-programming.html
38 \title Network Programming with Qt
39 \brief Programming applications with networking capabilities
41 The Qt Network module offers classes that allow you to write TCP/IP clients
42 and servers. It offers lower-level classes such as QTcpSocket,
43 QTcpServer and QUdpSocket that represent low level network concepts,
44 and high level classes such as QNetworkRequest, QNetworkReply and
45 QNetworkAccessManager to perform network operations using common protocols.
46 It also offers classes such as QNetworkConfiguration,
47 QNetworkConfigurationManager and QNetworkSession that implement bearer
52 \section1 Qt's Classes for Network Programming
54 The \l{Qt Network - C++ Classes} page contains a list of the C++ classes
57 \section1 High Level Network Operations for HTTP and FTP
59 The Network Access API is a collection of classes for performing
60 common network operations. The API provides an abstraction layer
61 over the specific operations and protocols used (for example,
62 getting and posting data over HTTP), and only exposes classes,
63 functions, and signals for general or high level concepts.
65 Network requests are represented by the QNetworkRequest class,
66 which also acts as a general container for information associated
67 with a request, such as any header information and the encryption
68 used. The URL specified when a request object is constructed
69 determines the protocol used for a request.
70 Currently HTTP, FTP and local file URLs are supported for uploading
73 The coordination of network operations is performed by the
74 QNetworkAccessManager class. Once a request has been created,
75 this class is used to dispatch it and emit signals to report on
76 its progress. The manager also coordinates the use of
77 \l{QNetworkCookieJar}{cookies} to store data on the client,
78 authentication requests, and the use of proxies.
80 Replies to network requests are represented by the QNetworkReply
81 class; these are created by QNetworkAccessManager when a request
82 is dispatched. The signals provided by QNetworkReply can be used
83 to monitor each reply individually, or developers may choose to
84 use the manager's signals for this purpose instead and discard
85 references to replies. Since QNetworkReply is a subclass of
86 QIODevice, replies can be handled synchronously or asynchronously;
87 i.e., as blocking or non-blocking operations.
89 Each application or library can create one or more instances of
90 QNetworkAccessManager to handle network communication.
92 \section1 Using TCP with QTcpSocket and QTcpServer
94 TCP (Transmission Control Protocol) is a low-level network
95 protocol used by most Internet protocols, including HTTP and FTP,
96 for data transfer. It is a reliable, stream-oriented,
97 connection-oriented transport protocol. It is particularly well
98 suited to the continuous transmission of data.
100 \image tcpstream.png A TCP Stream
102 The QTcpSocket class provides an interface for TCP. You can use
103 QTcpSocket to implement standard network protocols such as POP3,
104 SMTP, and NNTP, as well as custom protocols.
106 A TCP connection must be established to a remote host and port
107 before any data transfer can begin. Once the connection has been
108 established, the IP address and port of the peer are available
109 through QTcpSocket::peerAddress() and QTcpSocket::peerPort(). At
110 any time, the peer can close the connection, and data transfer
111 will then stop immediately.
113 QTcpSocket works asynchronously and emits signals to report status
114 changes and errors, just like QNetworkAccessManager. It
115 relies on the event loop to detect incoming data and to
116 automatically flush outgoing data. You can write data to the
117 socket using QTcpSocket::write(), and read data using
118 QTcpSocket::read(). QTcpSocket represents two independent streams
119 of data: one for reading and one for writing.
121 Since QTcpSocket inherits QIODevice, you can use it with
122 QTextStream and QDataStream. When reading from a QTcpSocket, you
123 must make sure that enough data is available by calling
124 QTcpSocket::bytesAvailable() beforehand.
126 If you need to handle incoming TCP connections (e.g., in a server
127 application), use the QTcpServer class. Call QTcpServer::listen()
128 to set up the server, and connect to the
129 QTcpServer::newConnection() signal, which is emitted once for
130 every client that connects. In your slot, call
131 QTcpServer::nextPendingConnection() to accept the connection and
132 use the returned QTcpSocket to communicate with the client.
134 Although most of its functions work asynchronously, it's possible
135 to use QTcpSocket synchronously (i.e., blocking). To get blocking
136 behavior, call QTcpSocket's waitFor...() functions; these suspend
137 the calling thread until a signal has been emitted. For example,
138 after calling the non-blocking QTcpSocket::connectToHost()
139 function, call QTcpSocket::waitForConnected() to block the thread
140 until the \l{QTcpSocket::connected()}{connected()} signal has
143 Synchronous sockets often lead to code with a simpler flow of
144 control. The main disadvantage of the waitFor...() approach is
145 that events won't be processed while a waitFor...() function is
146 blocking. If used in the GUI thread, this might freeze the
147 application's user interface. For this reason, we recommend that
148 you use synchronous sockets only in non-GUI threads. When used
149 synchronously, QTcpSocket doesn't require an event loop.
151 The \l{fortuneclient}{Fortune Client} and
152 \l{fortuneserver}{Fortune Server} examples show how to use
153 QTcpSocket and QTcpServer to write TCP client-server
154 applications. See also \l{blockingfortuneclient}{Blocking
155 Fortune Client} for an example on how to use a synchronous
156 QTcpSocket in a separate thread (without using an event loop),
157 and \l{threadedfortuneserver}{Threaded Fortune Server}
158 for an example of a multithreaded TCP server with one thread per
161 \section1 Using UDP with QUdpSocket
163 UDP (User Datagram Protocol) is a lightweight, unreliable,
164 datagram-oriented, connectionless protocol. It can be used when
165 reliability isn't important. For example, a server that reports
166 the time of day could choose UDP. If a datagram with the time of
167 day is lost, the client can simply make another request.
169 \image udppackets.png UDP Packets
171 The QUdpSocket class allows you to send and receive UDP
172 datagrams. It inherits QAbstractSocket, and it therefore shares
173 most of QTcpSocket's interface. The main difference is that
174 QUdpSocket transfers data as datagrams instead of as a continuous
175 stream of data. In short, a datagram is a data packet of limited
176 size (normally smaller than 512 bytes), containing the IP address
177 and port of the datagram's sender and receiver in addition to the
178 data being transferred.
180 QUdpSocket supports IPv4 broadcasting. Broadcasting is often used
181 to implement network discovery protocols, such as finding which
182 host on the network has the most free hard disk space. One host
183 broadcasts a datagram to the network that all other hosts
184 receive. Each host that receives a request then sends a reply
185 back to the sender with its current amount of free disk space.
186 The originator waits until it has received replies from all
187 hosts, and can then choose the server with most free space to
188 store data. To broadcast a datagram, simply send it to the
189 special address QHostAddress::Broadcast (255.255.255.255), or
190 to your local network's broadcast address.
192 QUdpSocket::bind() prepares the socket for accepting incoming
193 datagrams, much like QTcpServer::listen() for TCP servers.
194 Whenever one or more datagrams arrive, QUdpSocket emits the
195 \l{QUdpSocket::readyRead()}{readyRead()} signal. Call
196 QUdpSocket::readDatagram() to read the datagram.
198 The \l{broadcastsender}{Broadcast Sender} and
199 \l{broadcastreceiver}{Broadcast Receiver} examples show how to
200 write a UDP sender and a UDP receiver using Qt.
202 QUdpSocket also supports multicasting. The
203 \l{multicastsender}{Multicast Sender} and
204 \l{multicastreceiver}{Multicast Receiver} examples show how to use
205 write UDP multicast clients.
207 \section1 Resolving Host Names using QHostInfo
209 Before establishing a network connection, QTcpSocket and
210 QUdpSocket perform a name lookup, translating the host name
211 you're connecting to into an IP address. This operation is
212 usually performed using the DNS (Domain Name Service) protocol.
214 QHostInfo provides a static function that lets you perform such a
215 lookup yourself. By calling QHostInfo::lookupHost() with a host
216 name, a QObject pointer, and a slot signature, QHostInfo will
217 perform the name lookup and invoke the given slot when the
218 results are ready. The actual lookup is done in a separate
219 thread, making use of the operating system's own methods for
220 performing name lookups.
222 QHostInfo also provides a static function called
223 QHostInfo::fromName() that takes the host name as argument and
224 returns the results. In this case, the name lookup is performed
225 in the same thread as the caller. This overload is useful for
226 non-GUI applications or for doing name lookups in a separate,
227 non-GUI thread. (Calling this function in a GUI thread may cause
228 your user interface to freeze while the function blocks as
229 it performs the lookup.)
231 \section1 Support for Network Proxies
233 Network communication with Qt can be performed through proxies,
234 which direct or filter network traffic between local and remote
237 Individual proxies are represented by the QNetworkProxy class,
238 which is used to describe and configure the connection to a proxy.
239 Proxy types which operate on different levels of network communication
240 are supported, with SOCKS 5 support allowing proxying of network
241 traffic at a low level, and HTTP and FTP proxying working at the
242 protocol level. See QNetworkProxy::ProxyType for more information.
244 Proxying can be enabled on a per-socket basis or for all network
245 communication in an application. A newly opened socket can be
246 made to use a proxy by calling its QAbstractSocket::setProxy()
247 function before it is connected. Application-wide proxying can
248 be enabled for all subsequent socket connections through the use
249 of the QNetworkProxy::setApplicationProxy() function.
251 Proxy factories are used to create policies for proxy use.
252 QNetworkProxyFactory supplies proxies based on queries for specific
253 proxy types. The queries themselves are encoded in QNetworkProxyQuery
254 objects which enable proxies to be selected based on key criteria,
255 such as the purpose of the proxy (TCP, UDP, TCP server, URL request),
256 local port, remote host and port, and the protocol in use (HTTP, FTP,
259 QNetworkProxyFactory::proxyForQuery() is used to query the factory
260 directly. An application-wide policy for proxying can be implemented
261 by passing a factory to QNetworkProxyFactory::setApplicationProxyFactory()
262 and a custom proxying policy can be created by subclassing
263 QNetworkProxyFactory; see the class documentation for details.
265 \section1 Bearer Management Support
267 Bearer Management controls the connectivity state of the device such that
268 the application can start or stop network interfaces and roam
269 transparently between access points.
271 The QNetworkConfigurationManager class manages the list of network
272 configurations known to the device. A network configuration describes the
273 set of parameters used to start a network interface and is represented by
274 the QNetworkConfiguration class.
276 A network interface is started by openning a QNetworkSession based on a
277 given network configuration. In most situations creating a network session
278 based on the platform specified default network configuration is
279 appropriate. The default network configuration is returned by the
280 QNetworkConfigurationManager::defaultConfiguration() function.
282 On some platforms it is a platform requirement that the application open a
283 network session before any network operations can be performed. This can be
284 tested by the presents of the
285 QNetworkConfigurationManager::NetworkSessionRequired flag in the value
286 returned by the QNetworkConfigurationManager::capabilities() function.
288 \sa {Bearer Management}