简体   繁体   中英

QT QTcpSocket not receiving any data

I'm writing a C++ project in Qt Creator, and I have a QTcpSocket . It is connecting ok, but bytesAvailable() is always zero , even when I send data to it from another project I wrote in C#. I tested that the C# project is actually sending data by using another C# project, and it is sending the data correctly. Here is my code:

#include <QTcpSocket>
#include <QDebug>

void main()
{
    QTcpSocket *tcpSocket=new QTcpSocket();
    tcpSocket->connectToHost("127.0.0.1",8080);
    while(true)
    {
        if(tcpSocket->bytesAvailable()!=0)
        {
            qDebug()<<tcpSocket<-bytesAvailable();
        }
    }
    tcpSocket->disconnectFromHost();
}

Thanks. :D

First of all, all Qt programs need an application object to set up a lot of the internals of the framework. Insert the following as your first statement:

QCoreApplication app(argc, argv);

Secondly, the ordinary way of network programming in Qt is to use the event processing system. Since you don't seem to need that, you should use the blocking functions instead so that the operating system gets a chance to tell your application that data has arrived.

You must use waitForReadyRead() before trying to read from the socket.

Read the documentation for more detailed information on the blocking and non-blocking API functions.

You should replace line

if(tcpSocket->bytesAvailable!=0)

to

if(tcpSocket->bytesAvailable()!=0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM