CopperSpice API  1.9.1
QUdpSocket Class Reference

The QUdpSocket class provides a UDP socket. More...

Inheritance diagram for QUdpSocket:
QAbstractSocket QIODevice QObject

Public Methods

 QUdpSocket (QObject *parent=nullptr)
 
virtual ~QUdpSocket ()
 
bool hasPendingDatagrams () const
 
bool joinMulticastGroup (const QHostAddress &groupAddress)
 
bool joinMulticastGroup (const QHostAddress &groupAddress, const QNetworkInterface &interfaceId)
 
bool leaveMulticastGroup (const QHostAddress &groupAddress)
 
bool leaveMulticastGroup (const QHostAddress &groupAddress, const QNetworkInterface &interfaceId)
 
QNetworkInterface multicastInterface () const
 
qint64 pendingDatagramSize () const
 
qint64 readDatagram (char *data, qint64 maxlen, QHostAddress *address=nullptr, quint16 *port=nullptr)
 
void setMulticastInterface (const QNetworkInterface &interfaceId)
 
qint64 writeDatagram (const char *data, qint64 len, const QHostAddress &address, quint16 port)
 
qint64 writeDatagram (const QByteArray &datagram, const QHostAddress &address, quint16 port)
 
- Public Methods inherited from QAbstractSocket
 QAbstractSocket (SocketType socketType, QObject *parent)
 
virtual ~QAbstractSocket ()
 
void abort ()
 
bool atEnd () const override
 
bool bind (const QHostAddress &address, quint16 port=0, BindMode mode=DefaultForPlatform)
 
bool bind (quint16 port=0, BindMode mode=DefaultForPlatform)
 
qint64 bytesAvailable () const override
 
qint64 bytesToWrite () const override
 
bool canReadLine () const override
 
void close () override
 
virtual void connectToHost (const QHostAddress &address, quint16 port, OpenMode openMode=ReadWrite)
 
virtual void connectToHost (const QString &hostName, quint16 port, OpenMode openMode=ReadWrite, NetworkLayerProtocol protocol=AnyIPProtocol)
 
virtual void disconnectFromHost ()
 
SocketError error () const
 
bool flush ()
 
bool isSequential () const override
 
bool isValid () const
 
QHostAddress localAddress () const
 
quint16 localPort () const
 
PauseModes pauseMode () const
 
QHostAddress peerAddress () const
 
QString peerName () const
 
quint16 peerPort () const
 
QNetworkProxy proxy () const
 
qint64 readBufferSize () const
 
virtual void resume ()
 
void setPauseMode (PauseModes pauseMode)
 
void setProxy (const QNetworkProxy &networkProxy)
 
virtual void setReadBufferSize (qint64 size)
 
virtual bool setSocketDescriptor (qintptr socketDescriptor, SocketState socketState=ConnectedState, OpenMode openMode=ReadWrite)
 
virtual void setSocketOption (QAbstractSocket::SocketOption option, const QVariant &value)
 
virtual qintptr socketDescriptor () const
 
virtual QVariant socketOption (QAbstractSocket::SocketOption option)
 
SocketType socketType () const
 
SocketState state () const
 
bool waitForBytesWritten (int msecs=30000) override
 
virtual bool waitForConnected (int msecs=30000)
 
virtual bool waitForDisconnected (int msecs=30000)
 
bool waitForReadyRead (int msecs=30000) override
 
- Public Methods inherited from QIODevice
 QIODevice ()
 
 QIODevice (QObject *parent)
 
virtual ~QIODevice ()
 
QString errorString () const
 
bool getChar (char *c)
 
bool isOpen () const
 
bool isReadable () const
 
bool isTextModeEnabled () const
 
bool isWritable () const
 
virtual bool open (OpenMode mode)
 
OpenMode openMode () const
 
qint64 peek (char *data, qint64 maxSize)
 
QByteArray peek (qint64 maxSize)
 
virtual qint64 pos () const
 
bool putChar (char c)
 
qint64 read (char *data, qint64 maxSize)
 
QByteArray read (qint64 maxSize)
 
QByteArray readAll ()
 
qint64 readLine (char *data, qint64 maxSize)
 
QByteArray readLine (qint64 maxSize=0)
 
virtual bool reset ()
 
virtual bool seek (qint64 pos)
 
void setTextModeEnabled (bool enabled)
 
virtual qint64 size () const
 
void ungetChar (char c)
 
qint64 write (const char *data)
 
qint64 write (const char *data, qint64 maxSize)
 
qint64 write (const QByteArray &data)
 
- Public Methods inherited from QObject
 QObject (QObject *parent=nullptr)
 
 ~QObject ()
 
bool blockSignals (bool block)
 
const QList< QObject * > & children () const
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool connect (const QObject *sender, const QString &signalMethod, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
bool disconnect (const QObject *receiver, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod, const QString &location, const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
bool disconnect (const QString &signalMethod=QString (), const QObject *receiver=nullptr, const QString &slotMethod=QString ()) const
 
void dumpObjectInfo ()
 
void dumpObjectTree ()
 
QList< QStringdynamicPropertyNames () const
 
virtual bool event (QEvent *event)
 
virtual bool eventFilter (QObject *watched, QEvent *event)
 
template<typename T >
findChild (const QString &childName=QString ()) const
 
template<class T >
QList< T > findChildren (const QRegularExpression &regExp, Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
template<class T >
QList< T > findChildren (const QString &childName=QString (), Qt::FindChildOptions options=Qt::FindChildrenRecursively) const
 
bool inherits (const QString &className) const
 
void installEventFilter (QObject *filterObj)
 
bool isWidgetType () const
 
bool isWindowType () const
 
void killTimer (int id)
 
const QMetaObjectmetaObject () const
 
void moveToThread (QThread *targetThread)
 
QString objectName () const
 
QObject * parent () const
 
template<class T = QVariant>
property (const QString &name) const
 
void removeEventFilter (QObject *obj)
 
void setObjectName (const QString &name)
 
void setParent (QObject *parent)
 
bool setProperty (const QString &name, const QVariant &value)
 
bool signalsBlocked () const
 
int startTimer (int interval, Qt::TimerType timerType=Qt::CoarseTimer)
 
QThreadthread () const
 

Additional Inherited Members

- Public Typedefs inherited from QAbstractSocket
using BindMode = QFlags< BindFlag >
 
using PauseModes = QFlags< PauseMode >
 
- Public Typedefs inherited from QIODevice
using OpenMode = QFlags< OpenModeFlag >
 
- Public Types inherited from QAbstractSocket
enum  BindFlag
 
enum  NetworkLayerProtocol
 
enum  PauseMode
 
enum  SocketError
 
enum  SocketOption
 
enum  SocketState
 
enum  SocketType
 
- Public Types inherited from QIODevice
enum  OpenModeFlag
 
- Public Signals inherited from QAbstractSocket
void connected ()
 
void disconnected ()
 
void error (QAbstractSocket::SocketError socketError)
 
void hostFound ()
 
void proxyAuthenticationRequired (const QNetworkProxy &proxy, QAuthenticator *authenticator)
 
void stateChanged (QAbstractSocket::SocketState socketState)
 
- Public Signals inherited from QIODevice
void aboutToClose ()
 
void bytesWritten (qint64 bytes)
 
void readChannelFinished ()
 
void readyRead ()
 
- Public Signals inherited from QObject
void destroyed (QObject *obj=nullptr)
 
void objectNameChanged (const QString &objectName)
 
- Public Slots inherited from QObject
void deleteLater ()
 
- Static Public Methods inherited from QObject
static bool connect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool connect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection, const QString &location=QString ())
 
static bool connect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod, Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...), Qt::ConnectionType type=Qt::AutoConnection)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool connect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotLambda, Qt::ConnectionType type=Qt::AutoConnection)
 
static bool disconnect (const QObject *sender, const QMetaMethod &signalMethod, const QObject *receiver, const QMetaMethod &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QObject *receiver, const QString &slotMethod)
 
static bool disconnect (const QObject *sender, const QString &signalMethod, const QString &location, const QObject *receiver, const QString &slotMethod)
 
static bool disconnect (const QObject *sender, std::nullptr_t, const QObject *receiver, std::nullptr_t)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class SlotClass , class... SlotArgs, class SlotReturn >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, SlotReturn (SlotClass::*slotMethod)(SlotArgs...))
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, std::nullptr_t slotMethod=nullptr)
 
template<class Sender , class SignalClass , class... SignalArgs, class Receiver , class T >
static bool disconnect (const Sender *sender, void (SignalClass::*signalMethod)(SignalArgs...), const Receiver *receiver, T slotMethod)
 
static QMetaObjectstaticMetaObject ()
 
static QString tr (const char *text, const char *comment=nullptr, std::optional< int > numArg=std::optional< int >())
 
- Protected Methods inherited from QAbstractSocket
qint64 readData (char *data, qint64 maxlen) override
 
qint64 readLineData (char *data, qint64 maxlen) override
 
void setLocalAddress (const QHostAddress &address)
 
void setLocalPort (quint16 port)
 
void setPeerAddress (const QHostAddress &address)
 
void setPeerName (const QString &name)
 
void setPeerPort (quint16 port)
 
void setSocketError (SocketError socketError)
 
void setSocketState (SocketState state)
 
qint64 writeData (const char *data, qint64 len) override
 
- Protected Methods inherited from QIODevice
void setErrorString (const QString &errorString)
 
void setOpenMode (OpenMode openMode)
 
- Protected Methods inherited from QObject
virtual void childEvent (QChildEvent *event)
 
virtual void connectNotify (const QMetaMethod &signalMethod) const
 
virtual void customEvent (QEvent *event)
 
virtual void disconnectNotify (const QMetaMethod &signalMethod) const
 
bool isSignalConnected (const QMetaMethod &signalMethod) const
 
int receivers (const QString &signal) const
 
QObject * sender () const
 
int senderSignalIndex () const
 
virtual void timerEvent (QTimerEvent *event)
 
- Properties inherited from QObject
 objectName
 

Detailed Description

The QUdpSocket class provides a UDP socket.

UDP (User Datagram Protocol) is a lightweight, unreliable, datagram-oriented, connectionless protocol. It can be used when reliability is not important. QUdpSocket is a subclass of QAbstractSocket that allows you to send and receive UDP datagrams.

The most common way to use this class is to bind to an address and port using bind(), then call writeDatagram() and readDatagram() to transfer data. If you want to use the standard QIODevice functions read(), readLine(), write(), etc., you must first connect the socket directly to a peer by calling connectToHost().

The socket emits the bytesWritten() signal every time a datagram is written to the network. If you just want to send datagrams, you do not need to call bind().

The readyRead() signal is emitted whenever datagrams arrive. In that case, hasPendingDatagrams() returns true. Call pendingDatagramSize() to obtain the size of the first pending datagram, and readDatagram() to read it.

Note
An incoming datagram should be read when you receive the readyRead() signal, otherwise this signal will not be emitted for the next datagram.
void Server::initSocket()
{
udpSocket = new QUdpSocket(this);
udpSocket->bind(QHostAddress::LocalHost, 7755);
connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));
}
void Server::readPendingDatagrams()
{
while (udpSocket->hasPendingDatagrams()) {
QByteArray datagram;
datagram.resize(udpSocket->pendingDatagramSize());
quint16 senderPort;
udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
processTheDatagram(datagram);
}
}

QUdpSocket also supports UDP multicast. Use joinMulticastGroup() and leaveMulticastGroup() to control group membership, and QAbstractSocket::MulticastTtlOption and QAbstractSocket::MulticastLoopbackOption to set the TTL and loopback socket options. Use setMulticastInterface() to control the outgoing interface for multicast datagrams, and multicastInterface() to query it.

With QUdpSocket, you can also establish a virtual connection to a UDP server using connectToHost() and then use read() and write() to exchange datagrams without specifying the receiver for each datagram.

See also
QTcpSocket

Constructor & Destructor Documentation

QUdpSocket::QUdpSocket ( QObject parent = nullptr)
explicit

Creates a QUdpSocket object.

parent is passed to the QObject constructor.

See also
socketType()
QUdpSocket::~QUdpSocket ( )
virtual

Destroys the socket, closing the connection if necessary.

See also
close()

Method Documentation

bool QUdpSocket::hasPendingDatagrams ( ) const

Returns true if at least one datagram is waiting to be read, otherwise returns false.

See also
pendingDatagramSize(), readDatagram()
bool QUdpSocket::joinMulticastGroup ( const QHostAddress groupAddress)

Joins the multicast group specified by groupAddress on the default interface chosen by the operating system. The socket must be in BoundState, otherwise an error occurs. This method returns true if successful, otherwise it returns false and sets the socket error accordingly.

See also
leaveMulticastGroup()
bool QUdpSocket::joinMulticastGroup ( const QHostAddress groupAddress,
const QNetworkInterface interfaceId 
)

Joins the multicast group address groupAddress on the interface interfaceId.

See also
leaveMulticastGroup()
bool QUdpSocket::leaveMulticastGroup ( const QHostAddress groupAddress)

Leaves the multicast group specified by groupAddress on the default interface chosen by the operating system. The socket must be in BoundState, otherwise an error occurs.

This function returns true if successful, otherwise it returns false and sets the socket error accordingly.

See also
joinMulticastGroup()
bool QUdpSocket::leaveMulticastGroup ( const QHostAddress groupAddress,
const QNetworkInterface interfaceId 
)

Leaves the multicast group specified by groupAddress on the interface interfaceId.

See also
joinMulticastGroup()
QNetworkInterface QUdpSocket::multicastInterface ( ) const

Returns the interface for the outgoing interface for multicast datagrams. This corresponds to the IP_MULTICAST_IF socket option for IPv4 sockets and the IPV6_MULTICAST_IF socket option for IPv6 sockets. If no interface has been previously set, this function returns an invalid QNetworkInterface. The socket must be in BoundState, otherwise an invalid QNetworkInterface is returned.

See also
setMulticastInterface()
qint64 QUdpSocket::pendingDatagramSize ( ) const

Returns the size of the first pending UDP datagram. If there is no datagram available, this function returns -1.

See also
hasPendingDatagrams(), readDatagram()
qint64 QUdpSocket::readDatagram ( char *  data,
qint64  maxlen,
QHostAddress address = nullptr,
quint16 port = nullptr 
)

Receives a datagram no larger than maxlen bytes and stores it in data. The sender's host address and port is stored in address and port, unless the pointers are null. Returns the size of the datagram on success, otherwise returns -1.

If maxlen is too small, the rest of the datagram will be lost. To avoid loss of data, call pendingDatagramSize() to determine the size of the pending datagram before attempting to read it. If maxlen is 0 the datagram will be discarded.

See also
writeDatagram(), hasPendingDatagrams(), pendingDatagramSize()
void QUdpSocket::setMulticastInterface ( const QNetworkInterface interfaceId)

Sets the outgoing interface for multicast datagrams to the interfaceId. This corresponds to the IP_MULTICAST_IF socket option for IPv4 sockets and the IPV6_MULTICAST_IF socket option for IPv6 sockets. The socket must be in BoundState, otherwise this function does nothing.

See also
multicastInterface(), joinMulticastGroup(), leaveMulticastGroup()
qint64 QUdpSocket::writeDatagram ( const char *  data,
qint64  len,
const QHostAddress address,
quint16  port 
)

Sends the datagram at data of size len to the host address at port. Returns the number of bytes sent on success, otherwise returns -1.

Datagrams are always written as one block. The maximum size of a datagram is highly platform-dependent, but can be as low as 8192 bytes. If the datagram is too large, this function will return -1 and error() will return DatagramTooLargeError.

Sending datagrams larger than 512 bytes is in general disadvised, as even if they are sent successfully, they are likely to be fragmented by the IP layer before arriving at their final destination.

Warning
Calling this method on a connected UDP socket may result in an error and no packet being sent. If you are using a connected socket, use write() to send datagrams.
See also
readDatagram(), write()
qint64 QUdpSocket::writeDatagram ( const QByteArray datagram,
const QHostAddress address,
quint16  port 
)
inline

Sends the datagram to the host address at the given port.