tcp listen and receive text



  • Hi there,
    I have written a small Android app that sends an url link to a specified ip/port in my lan. The url is followed by a newline (\n).

    So far that works. If I run:

    ncat -k -l 192.168.1.100 6666
    

    on my Desktop Pc I can receive every url that I sent over the app.

    Now I want a Qt application that does the same instead of ncat.

    I wrote this little code but everytime I send the url the "newConnection" function gets called but appearently I dont get any bytes:

    MyServer::MyServer(QObject *parent)
    {
       server = new QTcpServer(this);
       connect(server,&QTcpServer::newConnection,this,&MyServer::newConnection);
    
       if(!server->listen(QHostAddress::Any,6666))
       {
           qDebug() << "Server could not start!";
       }
       else
       {
           qDebug() << "Server started!";
       }
    }
    
    void MyServer::newConnection()
    {
        QTcpSocket *socket = server->nextPendingConnection();
        if(socket->bytesAvailable())
        {
            qDebug() << socket->readAll();
        }
    }
    

    I also tried with:

    qDebug() << socket->bytesAvailable()
    

    and that gives me back always 0.
    Can someone give me a hint what I am doing wrong?



  • You have to wait for readyRead before reading.

    void MyServer::newConnection()
    {
        QTcpSocket *socket = server->nextPendingConnection();
    QObject::connect(socket,&QTcpSocket::readyRead,this,[socket]()->void{
        if(socket->bytesAvailable())
        {
            qDebug() << socket->readAll();
        }
    });
    }
    


  • great! works. Thanks a lot.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.