Reputation: 980
I want to use some standard QUdpSocket
methods to be exact read()
and readAll()
. So, according to the documentation of QUdpSocket
:
If you want to use the standard
QIODevice
functionsread()
,readLine()
,write()
, etc., you must first connect the socket directly to a peer by callingconnectToHost()
.
I call connectToHost()
directly after bind()
:
socket.bind(QHostAddress::LocalHost, 14560);
socket.connectToHost(QHostAddress::LocalHost, 14560);
Now it can read, but it doesn't emits readyRead()
signal. What is the proper way to use QIODevice
functions of QUdpSocket
?
DeviceReader.h:
class DeviceReader : public QObject {
Q_OBJECT
public:
DeviceReader() {}
void setDevice(QIODevice * device) {
_device = device;
connect(device, &QIODevice::readyRead, this, &DeviceReader::onDataReceived);
}
void onDataReceived() {
qDebug() << "received: " << _device->readAll();
}
private:
QIODevice * _device;
};
main.cpp:
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
DeviceReader reader;
QUdpSocket socket;
socket.bind(QHostAddress::LocalHost, 14560);
socket.connectToHost(QHostAddress::LocalHost, 14560);
reader.setDevice(&socket);
return a.exec();
}
Qt version is 5.7.0 clang x64. OS: macOS Sierra 10.12.2.
Upvotes: 0
Views: 913
Reputation: 980
From my point of view it is incorrect to use bind and connectToHost together.
bind method has to be used in cases of UDP server and connectToHost method has to be used for UDP client only. So just try to omit connectToHost call and you will receive incoming datagrams on 14560 port.
bind method description in Qt docs:
For UDP sockets, after binding, the signal QUdpSocket::readyRead() is emitted whenever a UDP datagram arrives on the specified address and port. Thus, This function is useful to write UDP servers.
Upvotes: 1