简体   繁体   English

QT QTcpSocket没有收到任何数据

[英]QT QTcpSocket not receiving any data

I'm writing a C++ project in Qt Creator, and I have a QTcpSocket . 我正在Qt Creator中编写一个C ++项目,并且有一个QTcpSocket It is connecting ok, but bytesAvailable() is always zero , even when I send data to it from another project I wrote in C#. 它连接正常,但是即使我从用C#编写的另一个项目向它发送数据时, bytesAvailable()也始终zero I tested that the C# project is actually sending data by using another C# project, and it is sending the data correctly. 我测试了C#项目实际上是通过使用另一个C#项目发送数据的,并且它可以正确发送数据。 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 :d

First of all, all Qt programs need an application object to set up a lot of the internals of the framework. 首先,所有Qt程序都需要一个应用程序对象来建立框架的许多内部结构。 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. 其次,在Qt中进行网络编程的普通方法是使用事件处理系统。 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. 在尝试从套接字读取之前,必须使用waitForReadyRead()

Read the documentation for more detailed information on the blocking and non-blocking API functions. 阅读文档以获取有关阻塞和非阻塞API函数的更多详细信息。

You should replace line 你应该换行

if(tcpSocket->bytesAvailable!=0)

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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