1
/****************************************************************************
3
** Copyright (C) 1992-2005 Trolltech AS. All rights reserved.
5
** This file is part of the network module of the Qt Toolkit.
7
** This file may be distributed under the terms of the Q Public License
8
** as defined by Trolltech AS of Norway and appearing in the file
9
** LICENSE.QPL included in the packaging of this file.
11
** This file may be distributed and/or modified under the terms of the
12
** GNU General Public License version 2 as published by the Free Software
13
** Foundation and appearing in the file LICENSE.GPL included in the
14
** packaging of this file.
16
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
17
** information about Qt Commercial License Agreements.
18
** See http://www.trolltech.com/qpl/ for QPL licensing information.
19
** See http://www.trolltech.com/gpl/ for GPL licensing information.
21
** Contact info@trolltech.com if any conditions of this licensing are
24
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
25
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27
****************************************************************************/
29
//#define QUDPSOCKET_DEBUG
34
\brief The QUdpSocket class provides a UDP socket.
39
UDP (User Datagram Protocol) is a lightweight, unreliable,
40
datagram-oriented, connectionless protocol. It can be used when
41
reliability isn't important. QUdpSocket is a subclass of
42
QAbstractSocket that allows you to send and receive UDP
45
The most common way to use this class is to bind to an address
46
and port using bind(), then call writeDatagram() and
47
readDatagram() to transfer data.
49
The socket emits the bytesWritten() signal every time a datagram
50
is written to the network. If you just want to send datagrams,
51
you don't need to call bind().
53
The readyRead() signal is emitted whenever datagrams arrive. In
54
that case, hasPendingDatagrams() returns true. Call
55
pendingDatagramSize() to obtain the size of the first pending
56
datagram, and readDatagram() to read it.
61
void Server::initSocket()
63
udpSocket = new QUdpSocket(this);
64
udpSocket->bind(QHostAddress::LocalHost, 7755);
66
connect(udpSocket, SIGNAL(readyRead()),
67
this, SLOT(readPendingDatagrams()));
70
void Server::readPendingDatagrams()
72
while (udpSocket->hasPendingDatagrams()) {
74
datagram.resize(udpSocket->pendingDatagramSize());
78
udpSocket->readDatagram(datagram.data(), datagram.size(),
79
&sender, &senderPort);
81
processTheDatagram(datagram);
86
With QUdpSocket, you can also establish a virtual connection to a
87
UDP server using connectToHost() and then use read() and write()
88
to exchange datagrams without specifying the receiver for each
91
The \l{network/broadcastsender}{Broadcast Sender} and
92
\l{network/broadcastreceiver}{Broadcast Receiver} examples
93
illustrate how to use QUdpSocket in applications.
97
#include "qhostaddress.h"
98
#include "qabstractsocket_p.h"
99
#include "qudpsocket.h"
101
#if defined(QT_NO_IPV6)
102
#define QT_ENSURE_INITIALIZED(a) do { \
103
QAbstractSocket::NetworkLayerProtocol proto = address.protocol(); \
104
if (proto == QUdpSocket::IPv6Protocol) { \
105
d_func()->socketError = QUdpSocket::UnsupportedSocketOperationError; \
106
setErrorString(QT_TRANSLATE_NOOP("QUdpSocket", "This platform does not support IPv6")); \
109
if (!d_func()->socketLayer.isValid() || d_func()->socketLayer.protocol() != proto) \
110
if (!d_func()->initSocketLayer(QUdpSocket::UdpSocket, proto)) \
114
#define QT_ENSURE_INITIALIZED(a) do { \
115
QAbstractSocket::NetworkLayerProtocol proto = address.protocol(); \
116
if (!d_func()->socketLayer.isValid() || d_func()->socketLayer.protocol() != proto) \
117
if (!d_func()->initSocketLayer(QUdpSocket::UdpSocket, proto)) \
121
#define QT_CHECK_BOUND(function, a) do { \
123
qWarning(function" called on a QUdpSocket when not in QUdpSocket::BoundState"); \
127
class QUdpSocketPrivate : public QAbstractSocketPrivate
129
Q_DECLARE_PUBLIC(QUdpSocket)
133
Creates a QUdpSocket object.
135
\a parent is passed to the QObject constructor.
139
QUdpSocket::QUdpSocket(QObject *parent)
140
: QAbstractSocket(UdpSocket, *new QUdpSocketPrivate, parent)
142
d_func()->isBuffered = false;
146
Destroys the socket, closing the connection if necessary.
150
QUdpSocket::~QUdpSocket()
155
Binds this socket to the address \a address and the port \a port.
156
When bound, the signal readyRead() is emitted whenever a UDP
157
datagram arrives on the specified address and port. This function
158
is useful to write UDP servers.
160
On success, the functions returns true and the socket enters
161
BoundState; otherwise it returns false.
165
bool QUdpSocket::bind(const QHostAddress &address, quint16 port)
167
QT_ENSURE_INITIALIZED(false);
169
bool result = d_func()->socketLayer.bind(address, port);
171
d_func()->socketError = d_func()->socketLayer.error();
172
setErrorString(d_func()->socketLayer.errorString());
173
emit error(d_func()->socketError);
177
d_func()->state = BoundState;
178
emit stateChanged(d_func()->state);
179
d_func()->readSocketNotifier->setEnabled(true);
185
Binds to QHostAddress:Any on port \a port.
187
bool QUdpSocket::bind(quint16 port)
189
return bind(QHostAddress::Any, port);
193
Returns true if at least one datagram is waiting to be read;
194
otherwise returns false.
196
\sa pendingDatagramSize(), readDatagram()
198
bool QUdpSocket::hasPendingDatagrams() const
200
QT_CHECK_BOUND("QUdpSocket::hasPendingDatagrams()", false);
201
return d_func()->socketLayer.hasPendingDatagrams();
205
Returns the size of the first pending UDP datagram. If there is
206
no datagram available, this function returns -1.
208
\sa hasPendingDatagrams(), readDatagram()
210
qint64 QUdpSocket::pendingDatagramSize() const
212
QT_CHECK_BOUND("QUdpSocket::pendingDatagramSize()", -1);
213
return d_func()->socketLayer.pendingDatagramSize();
217
Sends the datagram at \a data of size \a size to the host
218
address \a address at port \a port. Returns the number of
219
bytes sent on success; otherwise returns -1.
221
Datagrams are always written as one block. The maximum size of a
222
datagram is highly platform-dependent, but can be as low as 8192
223
bytes. If the datagram is too large, this function will return -1
224
and error() will return DatagramTooLargeError.
226
Sending datagrams larger than 512 bytes is in general disadvised,
227
as even if they are sent successfully, they are likely to be
228
fragmented by the IP layer before arriving at their final
233
qint64 QUdpSocket::writeDatagram(const char *data, qint64 size, const QHostAddress &address,
237
#if defined QUDPSOCKET_DEBUG
238
qDebug("QUdpSocket::writeDatagram(%p, %llu, \"%s\", %i)", data, size,
239
address.toString().toLatin1().constData(), port);
241
QT_ENSURE_INITIALIZED(-1);
242
qint64 sent = d->socketLayer.writeDatagram(data, size, address, port);
244
emit bytesWritten(sent);
246
d->socketError = d->socketLayer.error();
247
setErrorString(d->socketLayer.errorString());
248
emit error(d->socketError);
253
/*! \fn qint64 QUdpSocket::writeDatagram(const QByteArray &datagram,
254
const QHostAddress &host, quint16 port)
257
Sends the datagram \a datagram to the host address \a host and at
262
Receives a datagram no larger than \a maxSize bytes and stores
263
it in \a data. The sender's host address and port is stored in
264
*\a address and *\a port (unless the pointers are 0).
266
Returns the size of the datagram on success; otherwise returns
269
If \a maxSize is too small, the rest of the datagram will be
270
lost. To avoid loss of data, call pendingDatagramSize() to
271
determine the size of the pending datagram before attempting to
272
read it. If \a maxSize is 0, the datagram will be discarded.
274
\sa writeDatagram(), hasPendingDatagrams(), pendingDatagramSize()
276
qint64 QUdpSocket::readDatagram(char *data, qint64 maxSize, QHostAddress *address,
281
#if defined QUDPSOCKET_DEBUG
282
qDebug("QUdpSocket::readDatagram(%p, %llu, %p, %p)", data, maxSize, address, port);
284
QT_CHECK_BOUND("QUdpSocket::readDatagram()", -1);
285
qint64 readBytes = d->socketLayer.readDatagram(data, maxSize, address, port);
287
d->socketError = d->socketLayer.error();
288
setErrorString(d->socketLayer.errorString());
289
emit error(d->socketError);
291
d->readSocketNotifier->setEnabled(true);