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