QUdpSocket issue
Solved
General and Desktop
-
Hi,
I have a simple udp socket server. It recives what hosts write on, but it can't answer them. i get QIODevice::write (QUdpSocket): device not open when i try to call write(). Can please someone tell me what is missing ?int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QUdpSocket *udpSrv = new QUdpSocket(); udpSrv->bind(QHostAddress::LocalHost, 1234); QObject::connect(udpSrv,&QUdpSocket:: bytesWritten,[&](){ qDebug()<<"Server answered !"; // }); QObject::connect(udpSrv, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error),[&]() { qDebug()<< "Error : " << udpSrv->errorString(); }); QObject::connect(udpSrv,&QUdpSocket::readyRead,[&](){ QByteArray buffer; QHostAddress sender; quint16 senderPort; buffer.resize(static_cast<int>(udpSrv->pendingDatagramSize())); udpSrv->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort); QString req = QString::fromStdString(buffer.toStdString()); qDebug()<<"client : " << req; if(req=="Hi"){ udpSrv->write("Hello!"); // QIODevice::write (QUdpSocket): device not open } else{ udpSrv->write("Say Hello First !"); // QIODevice::write (QUdpSocket): device not open } }); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); }
-
@LeLev
you should rather use QUdpSocket::writeDatagram()
but first before anything else you should read the docs and/or at least one of the official examples... -
-
@raven-worx
now i'm able to write to the socket, but the tool i use as client (Packet Sender) does not receive anything, do you have an idea why ?QString resp = "Hello client !"; qint64 nwritten = udpSrv->writeDatagram(resp.toLatin1(),resp.length(),QHostAddress::LocalHost,1234); qDebug()<< "wrote : " << nwritten; // output 14
edit
i fixed, last parameter must be senderPort instead of 1234
writeDatagram(resp.toLatin1(),resp.length(),QHostAddress::LocalHost,senderPort)