Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
network-programming.qdoc
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only
3
4/*!
5 \group network
6 \title Network Programming API
7 \brief Classes for Network Programming
8
9 \ingroup groups
10*/
11
12/*!
13 \page qtnetwork-programming.html
14 \title Network Programming with Qt
15 \brief Programming applications with networking capabilities
16
17 The Qt Network module offers classes that allow you to write TCP/IP clients
18 and servers. It offers lower-level classes such as QTcpSocket,
19 QTcpServer and QUdpSocket that represent low level network concepts,
20 and high level classes such as QNetworkRequest, QNetworkReply and
21 QNetworkAccessManager to perform network operations using common protocols.
22
23 Qt Network also provides an API for Transport Layer Security (TLS) and
24 security functions using a native TLS backend, the \l{OpenSSL Toolkit}, or
25 any appropriate TLS plugin. Refer to the
26 \l{Secure Sockets Layer (SSL) Classes} for more information.
27
28 \section1 Qt's Classes for Network Programming
29
30 The \l{Qt Network C++ Classes} page contains a list of the C++ classes
31 in Qt Network.
32
33 \section1 High Level Network Operations for HTTP
34
35 The Network Access API is a collection of classes for performing
36 common network operations. The API provides an abstraction layer
37 over the specific operations and protocols used (for example,
38 getting and posting data over HTTP), and only exposes classes,
39 functions, and signals for general or high level concepts.
40
41 Network requests are represented by the QNetworkRequest class,
42 which also acts as a general container for information associated
43 with a request, such as any header information and the encryption
44 used. The URL specified when a request object is constructed
45 determines the protocol used for a request.
46 Currently HTTP and local file URLs are supported for uploading
47 and downloading.
48
49 The coordination of network operations is performed by the
50 QNetworkAccessManager class. Once a request has been created,
51 this class is used to dispatch it and emit signals to report on
52 its progress. The manager also coordinates the use of
53 \l{QNetworkCookieJar}{cookies} to store data on the client,
54 authentication requests, and the use of proxies.
55
56 Replies to network requests are represented by the QNetworkReply
57 class; these are created by QNetworkAccessManager when a request
58 is dispatched. The signals provided by QNetworkReply can be used
59 to monitor each reply individually, or developers may choose to
60 use the manager's signals for this purpose instead and discard
61 references to replies. Since QNetworkReply is a subclass of
62 QIODevice, replies can be handled synchronously or asynchronously;
63 i.e., as blocking or non-blocking operations.
64
65 Each application or library can create one or more instances of
66 QNetworkAccessManager to handle network communication.
67
68 \section1 Using TCP with QTcpSocket and QTcpServer
69
70 TCP (Transmission Control Protocol) is a low-level network
71 protocol used by most Internet protocols, including HTTP and FTP,
72 for data transfer. It is a reliable, stream-oriented,
73 connection-oriented transport protocol. It is particularly well
74 suited to the continuous transmission of data.
75
76 \image tcpstream.png A TCP Stream
77
78 The QTcpSocket class provides an interface for TCP. You can use
79 QTcpSocket to implement standard network protocols such as POP3,
80 SMTP, and NNTP, as well as custom protocols.
81
82 A TCP connection must be established to a remote host and port
83 before any data transfer can begin. Once the connection has been
84 established, the IP address and port of the peer are available
85 through QTcpSocket::peerAddress() and QTcpSocket::peerPort(). At
86 any time, the peer can close the connection, and data transfer
87 will then stop immediately.
88
89 QTcpSocket works asynchronously and emits signals to report status
90 changes and errors, just like QNetworkAccessManager. It
91 relies on the event loop to detect incoming data and to
92 automatically flush outgoing data. You can write data to the
93 socket using QTcpSocket::write(), and read data using
94 QTcpSocket::read(). QTcpSocket represents two independent streams
95 of data: one for reading and one for writing.
96
97 Since QTcpSocket inherits QIODevice, you can use it with
98 QTextStream and QDataStream. When reading from a QTcpSocket, you
99 must make sure that enough data is available by calling
100 QTcpSocket::bytesAvailable() beforehand.
101
102 If you need to handle incoming TCP connections (e.g., in a server
103 application), use the QTcpServer class. Call QTcpServer::listen()
104 to set up the server, and connect to the
105 QTcpServer::newConnection() signal, which is emitted once for
106 every client that connects. In your slot, call
107 QTcpServer::nextPendingConnection() to accept the connection and
108 use the returned QTcpSocket to communicate with the client.
109
110 Although most of its functions work asynchronously, it's possible
111 to use QTcpSocket synchronously (i.e., blocking). To get blocking
112 behavior, call QTcpSocket's waitFor...() functions; these suspend
113 the calling thread until a signal has been emitted. For example,
114 after calling the non-blocking QTcpSocket::connectToHost()
115 function, call QTcpSocket::waitForConnected() to block the thread
116 until the \l{QTcpSocket::connected()}{connected()} signal has
117 been emitted.
118
119 Synchronous sockets often lead to code with a simpler flow of
120 control. The main disadvantage of the waitFor...() approach is
121 that events won't be processed while a waitFor...() function is
122 blocking. If used in the GUI thread, this might freeze the
123 application's user interface. For this reason, we recommend that
124 you use synchronous sockets only in non-GUI threads. When used
125 synchronously, QTcpSocket doesn't require an event loop.
126
127 The \l{fortuneclient}{Fortune Client} and
128 \l{fortuneserver}{Fortune Server} examples show how to use
129 QTcpSocket and QTcpServer to write TCP client-server
130 applications. See also \l{blockingfortuneclient}{Blocking
131 Fortune Client} for an example on how to use a synchronous
132 QTcpSocket in a separate thread (without using an event loop),
133 and \l{threadedfortuneserver}{Threaded Fortune Server}
134 for an example of a multithreaded TCP server with one thread per
135 active client.
136
137 \section1 Using UDP with QUdpSocket
138
139 UDP (User Datagram Protocol) is a lightweight, unreliable,
140 datagram-oriented, connectionless protocol. It can be used when
141 reliability isn't important. For example, a server that reports
142 the time of day could choose UDP. If a datagram with the time of
143 day is lost, the client can simply make another request.
144
145 \image udppackets.png UDP Packets
146
147 The QUdpSocket class allows you to send and receive UDP
148 datagrams. It inherits QAbstractSocket, and it therefore shares
149 most of QTcpSocket's interface. The main difference is that
150 QUdpSocket transfers data as datagrams instead of as a continuous
151 stream of data. In short, a datagram is a data packet of limited
152 size (normally smaller than 512 bytes), containing the IP address
153 and port of the datagram's sender and receiver in addition to the
154 data being transferred.
155
156 QUdpSocket supports IPv4 broadcasting. Broadcasting is often used
157 to implement network discovery protocols, such as finding which
158 host on the network has the most free hard disk space. One host
159 broadcasts a datagram to the network that all other hosts
160 receive. Each host that receives a request then sends a reply
161 back to the sender with its current amount of free disk space.
162 The originator waits until it has received replies from all
163 hosts, and can then choose the server with most free space to
164 store data. To broadcast a datagram, simply send it to the
165 special address QHostAddress::Broadcast (255.255.255.255), or
166 to your local network's broadcast address.
167
168 QUdpSocket::bind() prepares the socket for accepting incoming
169 datagrams, much like QTcpServer::listen() for TCP servers.
170 Whenever one or more datagrams arrive, QUdpSocket emits the
171 \l{QUdpSocket::readyRead()}{readyRead()} signal. Call
172 QUdpSocket::readDatagram() to read the datagram.
173
174 The \l{broadcastsender}{Broadcast Sender} and
175 \l{broadcastreceiver}{Broadcast Receiver} examples show how to
176 write a UDP sender and a UDP receiver using Qt.
177
178 QUdpSocket also supports multicasting. The
179 \l{multicastsender}{Multicast Sender} and
180 \l{multicastreceiver}{Multicast Receiver} examples show how to use
181 write UDP multicast clients.
182
183 \section1 Resolving Host Names Using QHostInfo
184
185 Before establishing a network connection, QTcpSocket and
186 QUdpSocket perform a name lookup, translating the host name
187 you're connecting to into an IP address. This operation is
188 usually performed using the DNS (Domain Name Service) protocol.
189
190 QHostInfo provides a static function that lets you perform such a
191 lookup yourself. By calling QHostInfo::lookupHost() with a host
192 name, a QObject pointer, and a slot signature, QHostInfo will
193 perform the name lookup and invoke the given slot when the
194 results are ready. The actual lookup is done in a separate
195 thread, making use of the operating system's own methods for
196 performing name lookups.
197
198 QHostInfo also provides a static function called
199 QHostInfo::fromName() that takes the host name as argument and
200 returns the results. In this case, the name lookup is performed
201 in the same thread as the caller. This overload is useful for
202 non-GUI applications or for doing name lookups in a separate,
203 non-GUI thread. (Calling this function in a GUI thread may cause
204 your user interface to freeze while the function blocks as
205 it performs the lookup.)
206
207 \section1 Support for Network Proxies
208
209 Network communication with Qt can be performed through proxies,
210 which direct or filter network traffic between local and remote
211 connections.
212
213 Individual proxies are represented by the QNetworkProxy class,
214 which is used to describe and configure the connection to a proxy.
215 Proxy types which operate on different levels of network communication
216 are supported, with SOCKS 5 support allowing proxying of network
217 traffic at a low level, and HTTP and FTP proxying working at the
218 protocol level. See QNetworkProxy::ProxyType for more information.
219
220 Proxying can be enabled on a per-socket basis or for all network
221 communication in an application. A newly opened socket can be
222 made to use a proxy by calling its QAbstractSocket::setProxy()
223 function before it is connected. Application-wide proxying can
224 be enabled for all subsequent socket connections through the use
225 of the QNetworkProxy::setApplicationProxy() function.
226
227 Proxy factories are used to create policies for proxy use.
228 QNetworkProxyFactory supplies proxies based on queries for specific
229 proxy types. The queries themselves are encoded in QNetworkProxyQuery
230 objects which enable proxies to be selected based on key criteria,
231 such as the purpose of the proxy (TCP, UDP, TCP server, URL request),
232 local port, remote host and port, and the protocol in use (HTTP, FTP,
233 etc.).
234
235 QNetworkProxyFactory::proxyForQuery() is used to query the factory
236 directly. An application-wide policy for proxying can be implemented
237 by passing a factory to QNetworkProxyFactory::setApplicationProxyFactory()
238 and a custom proxying policy can be created by subclassing
239 QNetworkProxyFactory; see the class documentation for details.
240*/