Network Programming with Qt¶
Programming applications with networking capabilities
The Qt Network module offers classes that allow you to write TCP/IP clients and servers. It offers lower-level classes such as
QTcpSocket
,QTcpServer
andQUdpSocket
that represent low level network concepts, and high level classes such asQNetworkRequest
,QNetworkReply
andQNetworkAccessManager
to perform network operations using common protocols. It also offers classes such asQNetworkConfiguration
,QNetworkConfigurationManager
andQNetworkSession
that implement bearer management.
Qt’s Classes for Network Programming¶
The Qt Network C++ Classes page contains a list of the C++ classes in Qt Network.
High Level Network Operations for HTTP and FTP¶
The Network Access API is a collection of classes for performing common network operations. The API provides an abstraction layer over the specific operations and protocols used (for example, getting and posting data over HTTP), and only exposes classes, functions, and signals for general or high level concepts.
Network requests are represented by the
QNetworkRequest
class, which also acts as a general container for information associated with a request, such as any header information and the encryption used. The URL specified when a request object is constructed determines the protocol used for a request. Currently HTTP, FTP and local file URLs are supported for uploading and downloading.The coordination of network operations is performed by the
QNetworkAccessManager
class. Once a request has been created, this class is used to dispatch it and emit signals to report on its progress. The manager also coordinates the use ofcookies
to store data on the client, authentication requests, and the use of proxies.Replies to network requests are represented by the
QNetworkReply
class; these are created byQNetworkAccessManager
when a request is dispatched. The signals provided byQNetworkReply
can be used to monitor each reply individually, or developers may choose to use the manager’s signals for this purpose instead and discard references to replies. SinceQNetworkReply
is a subclass ofQIODevice
, replies can be handled synchronously or asynchronously; i.e., as blocking or non-blocking operations.Each application or library can create one or more instances of
QNetworkAccessManager
to handle network communication.
Using TCP with QTcpSocket and QTcpServer¶
TCP (Transmission Control Protocol) is a low-level network protocol used by most Internet protocols, including HTTP and FTP, for data transfer. It is a reliable, stream-oriented, connection-oriented transport protocol. It is particularly well suited to the continuous transmission of data.
The
QTcpSocket
class provides an interface for TCP. You can useQTcpSocket
to implement standard network protocols such as POP3, SMTP, and NNTP, as well as custom protocols.A TCP connection must be established to a remote host and port before any data transfer can begin. Once the connection has been established, the IP address and port of the peer are available through
peerAddress()
andpeerPort()
. At any time, the peer can close the connection, and data transfer will then stop immediately.
QTcpSocket
works asynchronously and emits signals to report status changes and errors, just likeQNetworkAccessManager
. It relies on the event loop to detect incoming data and to automatically flush outgoing data. You can write data to the socket usingwrite()
, and read data usingread()
.QTcpSocket
represents two independent streams of data: one for reading and one for writing.Since
QTcpSocket
inheritsQIODevice
, you can use it withQTextStream
andQDataStream
. When reading from aQTcpSocket
, you must make sure that enough data is available by callingbytesAvailable()
beforehand.If you need to handle incoming TCP connections (e.g., in a server application), use the
QTcpServer
class. Calllisten()
to set up the server, and connect to thenewConnection()
signal, which is emitted once for every client that connects. In your slot, callnextPendingConnection()
to accept the connection and use the returnedQTcpSocket
to communicate with the client.Although most of its functions work asynchronously, it’s possible to use
QTcpSocket
synchronously (i.e., blocking). To get blocking behavior, callQTcpSocket
‘s waitFor…() functions; these suspend the calling thread until a signal has been emitted. For example, after calling the non-blockingconnectToHost()
function, callwaitForConnected()
to block the thread until theconnected()
signal has been emitted.Synchronous sockets often lead to code with a simpler flow of control. The main disadvantage of the waitFor…() approach is that events won’t be processed while a waitFor…() function is blocking. If used in the GUI thread, this might freeze the application’s user interface. For this reason, we recommend that you use synchronous sockets only in non-GUI threads. When used synchronously,
QTcpSocket
doesn’t require an event loop.The Fortune Client and Fortune Server examples show how to use
QTcpSocket
andQTcpServer
to write TCP client-server applications. See also Blocking Fortune Client for an example on how to use a synchronousQTcpSocket
in a separate thread (without using an event loop), and Threaded Fortune Server for an example of a multithreaded TCP server with one thread per active client.
Using UDP with QUdpSocket¶
UDP (User Datagram Protocol) is a lightweight, unreliable, datagram-oriented, connectionless protocol. It can be used when reliability isn’t important. For example, a server that reports the time of day could choose UDP. If a datagram with the time of day is lost, the client can simply make another request.
The
QUdpSocket
class allows you to send and receive UDP datagrams. It inheritsQAbstractSocket
, and it therefore shares most ofQTcpSocket
‘s interface. The main difference is thatQUdpSocket
transfers data as datagrams instead of as a continuous stream of data. In short, a datagram is a data packet of limited size (normally smaller than 512 bytes), containing the IP address and port of the datagram’s sender and receiver in addition to the data being transferred.
QUdpSocket
supports IPv4 broadcasting. Broadcasting is often used to implement network discovery protocols, such as finding which host on the network has the most free hard disk space. One host broadcasts a datagram to the network that all other hosts receive. Each host that receives a request then sends a reply back to the sender with its current amount of free disk space. The originator waits until it has received replies from all hosts, and can then choose the server with most free space to store data. To broadcast a datagram, simply send it to the special addressBroadcast
(255.255.255.255), or to your local network’s broadcast address.
bind()
prepares the socket for accepting incoming datagrams, much likelisten()
for TCP servers. Whenever one or more datagrams arrive,QUdpSocket
emits thereadyRead()
signal. CallreadDatagram()
to read the datagram.The Broadcast Sender and Broadcast Receiver examples show how to write a UDP sender and a UDP receiver using Qt.
QUdpSocket
also supports multicasting. The Multicast Sender and Multicast Receiver examples show how to use write UDP multicast clients.
Resolving Host Names Using QHostInfo¶
Before establishing a network connection,
QTcpSocket
andQUdpSocket
perform a name lookup, translating the host name you’re connecting to into an IP address. This operation is usually performed using the DNS (Domain Name Service) protocol.
QHostInfo
provides a static function that lets you perform such a lookup yourself. By callinglookupHost()
with a host name, aQObject
pointer, and a slot signature,QHostInfo
will perform the name lookup and invoke the given slot when the results are ready. The actual lookup is done in a separate thread, making use of the operating system’s own methods for performing name lookups.
QHostInfo
also provides a static function calledfromName()
that takes the host name as argument and returns the results. In this case, the name lookup is performed in the same thread as the caller. This overload is useful for non-GUI applications or for doing name lookups in a separate, non-GUI thread. (Calling this function in a GUI thread may cause your user interface to freeze while the function blocks as it performs the lookup.)
Support for Network Proxies¶
Network communication with Qt can be performed through proxies, which direct or filter network traffic between local and remote connections.
Individual proxies are represented by the
QNetworkProxy
class, which is used to describe and configure the connection to a proxy. Proxy types which operate on different levels of network communication are supported, with SOCKS 5 support allowing proxying of network traffic at a low level, and HTTP and FTP proxying working at the protocol level. SeeProxyType
for more information.Proxying can be enabled on a per-socket basis or for all network communication in an application. A newly opened socket can be made to use a proxy by calling its
setProxy()
function before it is connected. Application-wide proxying can be enabled for all subsequent socket connections through the use of thesetApplicationProxy()
function.Proxy factories are used to create policies for proxy use.
QNetworkProxyFactory
supplies proxies based on queries for specific proxy types. The queries themselves are encoded inQNetworkProxyQuery
objects which enable proxies to be selected based on key criteria, such as the purpose of the proxy (TCP, UDP, TCP server, URL request), local port, remote host and port, and the protocol in use (HTTP, FTP, etc.).
proxyForQuery()
is used to query the factory directly. An application-wide policy for proxying can be implemented by passing a factory tosetApplicationProxyFactory()
and a custom proxying policy can be created by subclassingQNetworkProxyFactory
; see the class documentation for details.
© 2022 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.