Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |

# Network Module

The network module offers classes to make network programming easier and portable. It offers both high-level classes such as QHttp and QFtp that implement specific application-level protocols, and lower-level classes such as QTcpSocket, QTcpServer, and QUdpSocket, that enable you to write your own TCP/IP clients and servers.

This document is an overview of the main classes in the network module. See the individual classes' reference documentation for details.

- Writing HTTP and FTP Clients with QHttp and QFtp
- Using TCP with QTcpSocket
- Using UDP with QUdpSocket

## Writing HTTP and FTP Clients with QHttp and QFtp

HTTP (Hypertext Transfer Protocol) is an application-level network protocol used mainly for downloading HTML and XML files, but it is also used as a high-level transport protocol for any types of data. For example, HTTP is often used for transferring purchase orders over the Internet. In contrast, FTP (File Transfer Protocol) is a protocol used almost exclusively for browsing remote directories and transferring files.

HTTP is a simpler protocol than FTP in many ways. It uses only one network connection, while FTP uses two (one for sending commands, and one for transferring data). HTTP is a stateless protocol; requests and responses are always self-contained. The FTP protocol has a state and requires the client to send several commands before the file transfer takes place.

In practice, HTTP clients often use separate connections for separate requests, whereas FTP clients establish one connection and keep it open throughout the session.

The QHttp and QFtp classes provide client-side support for HTTP and FTP. Since the two protocols are used to solve the same problems, the QHttp and QFtp classes have many features in common:

- Non-blocking behavior. QHttp and QFtp are asynchronous. You can schedule a series of commands (also called "requests" for HTTP). The commands are executed later, when control goes back to Qt's event loop.
- Command IDs. Each command has a unique ID number that you can use to follow the execution of the command. For example, QFtp emits the commandStarted() and commandFinished() signal with the command ID for each command that is executed. QHttp has a requestStarted() and a requestFinished() signal that works the same way.
- Data transfer progress indicators. QHttp and QFtp emits signals whenever data is transferred (QFtp::dataTransferProgress(), QHttp::dataReadProgress(), and QHttp::dataSendProgress()). You can connect these signals to QProgressBar::setProgress() or QProgressDialog::setProgress().
- QIODevice support. Both classes support convenient uploading of and downloading to QIODevices, in addition to a QByteArray-based API.

There are two main ways of using QHttp and QFtp. The most common approach is to keep track of the command IDs and follow the execution of every command by connecting to the appropriate signals. The other approach is to schedule all commands at once and only connect to the done() signal, which is emitted when all scheduled commands have been executed. The first approach requires more work, but it gives you more control over the execution of individual commands and allows you to initiate new commands based on the result of a previous command. It also enables you to provide detailed feedback to the user.

The network/http and network/ftp examples illustrate how to write an HTTP and an FTP client.

Writing your own HTTP or FTP server is possible using the lower-level classes QTcpSocket and QTcpServer.

## Using TCP with QTcpSocket

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 especially well suited for continuous transmission of data.

The QTcpSocket class provides an interface for TCP. You can use QTcpSocket to implement standard network protocols such as POP3, SMTP, and NNTP, as well as proprietary 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 QTcpSocket::peerAddress() and QTcpSocket::peerPort(). At any time, the peer can close the connection, and data transfer will then stop immediately.

By default, QTcpSocket works asynchronously and emits signals to report status changes and errors, just like QHttp and QFtp. You can write data to the socket using QTcpSocket::write(), and read data using QTcpSocket::read(). QTcpSocket represents two independent streams of data: one for reading and one for writing.

Since QTcpSocket inherits QIODevice, you can use it with QTextStream and QDataStream. When reading from a QTcpSocket, you must make sure that enough data is available by calling QTcpSocket::bytesAvailable() beforehand.

If you need to handle incoming TCP connections (e.g., in a server application), use the QTcpServer class. Call QTcpServer::listen() to set up the server, and connect to the QTcpServer::newConnection() signal, which is emitted once for every client that connects. In your slot, call QTcpServer::nextPendingConnection() to accept the connection and use the returned QTcpSocket to communicate with the client.

QTcpSocket can be set to operate like a synchronous QIODevice (like QFile) by calling QTcpSocket::setBlocking(true). Signals are emitted as usual, but certain functions like QTcpSocket::connectToHost(), QTcpSocket::read(), and QTcpSocket::write() will suspend the thread in which they are running until the operation finishes. If the thread is the GUI thread, the user interface will potentially freeze. For this reason, QTcpSocket should only be used synchronously from a non-GUI thread or in a non-GUI application.

QTcpSocket and QTcpServer can be used without an event loop. In addition, the classes are reentrant, meaning that distinct instances of the classes can be used simultaneously in different threads.

Note that without an event loop, Qt is unable to notify QTcpSocket of incoming data, and QTcpSocket is unable to automatically flush outgoing data. Calling QTcpSocket::setBlocking(true) is the best way to avoid these problems. The alternative is to fall QTcpSocket::flush() whenever QTcpSocket::bytesToWrite() returns a non-zero value. You must then also call QTcpSocket::flush() manually to write data to the socket, and QTcpSocket::waitForReadyRead() to get the QTcpSocket::readyRead() signal.

The network/fortuneclient and network/fortuneserver examples show how to use QTcpSocket and QTcpServer to write TCP client-server applications. See also network/blockingfortuneclient for an example on how to use a synchronous QTcpSocket in a separate thread, without using an event loop.

## 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 inherits QAbstractSocket, and it therefore shares most of QTcpSocket's interface. The main difference is that QUdpSocket 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 address QHostAddress::Broadcast (255.255.255.255), or to your local network's broadcast address.

QUdpSocket::bind() prepares the socket for accepting incoming datagrams, much like QTcpServer::listen() for TCP servers. Whenever one or more datagrams arrive, QUdpSocket emits the readyRead() signal. Call QUdpSocket::readDatagram() to read the datagram.

The network/broadcastsender and network/broadcastreceiver examples show how to write a UDP sender and a UDP receiver using Qt.