Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

I am getting an error QIODevice::read (QUdpSocket): device not open



  • I am trying to create a UDP server , Client application
    but it throws the error as QIODevice::read (QUdpSocket): device not open . Below is my code
    , Kindly suggest what change should i do

    server.cpp

    QUdpSocket *socket;
    socket = new QUdpSocket(this);
    socket->bind(QHostAddress::Any, 1234);
    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
    
    void CQudpSocket::writeData()
    {
    QString str = "Hello";
    socket->writeDatagram(str.toLatin1().data(),str.length(),QHostAddress::Any,1234);
    //socket->write(str.toLatin1().data(),str.length());
    }
    void CQudpSocket::readyRead()
    {
    QString str1;
    socket->read(str1.toLatin1().data(),6);
    emit sig_recvData(str1);
    }
    

    mainwindow.cpp

       MainWindow::MainWindow(QWidget *parent) :
       
           QMainWindow(parent),
       
           ui(new Ui::MainWindow)
       
       {
       ui->setupUi(this);
        connect(&udpsocket,SIGNAL(sig_recvData(QString)),this,SLOT(PrintLog(QString)));
       }
       MainWindow::~MainWindow()
       {
       delete ui;
       }
       void MainWindow::PrintLog(QString str)
       {
       ui->textEdit->append(str);
       }
       void MainWindow::on_pushButton_clicked()
       {
       udpsocket.writeData();
       }
    

    client.cpp

     socket =  new QUdpSocket(this);
     connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
    
     void CQudpSocket::writeData()
     {
      QString str = "Hello";
     socket->writeDatagram(str.toLatin1().data(),str.length(),QHostAddress::LocalHost,1234);
     }
     void CQudpSocket::readyRead()
     {
     QString str1;
     socket->read(str1.toLatin1().data(),6);
     emit sig_recvData(str1);
     }
     
     void CQudpSocket::connectHost()
     {
     socket->connectToHost(QHostAddress::LocalHost, 1234);
     }
    

    mainwindow.cpp

       MainWindow::MainWindow(QWidget *parent) :
      QMainWindow(parent),
    ui(new Ui::MainWindow)
     {
    ui->setupUi(this);
    connect(&udpsocket,SIGNAL(sig_recvData(QString)),this,SLOT(PrintLog(QString)));
        }
    
     void MainWindow::on_pushButton_clicked()
     {
     udpsocket.writeData();
     }
     void MainWindow::PrintLog(QString str)
     {
     ui->textEdit->append(str);
     }
     void MainWindow::on_pushButton_2_clicked()
     {
     udpsocket.connectHost();
     }

  • Qt Champions 2019

    QUdpSocket receives datagrams which should be read with QUdpSocket::readDatagram(): https://doc.qt.io/qt-5/qudpsocket.html#details


Log in to reply