Qt:使用QTcpSocket - >我可以在socket上写,但我不能读...

时间:2016-09-26 09:13:54

标签: c++ qt sockets tcp

我在xUbuntu 14.04上使用Qt 4.8 GCC 32bit 我有一段代码,一个TCP服务器,我用它来获取一些远程命令并发回一些答案 - 通过TCP套接字:

struct _MyRequest
{
    unsigned long   Request;
    unsigned long   Data;
} __attribute__((packed));

struct _MyAnswer
{
    unsigned long   Error;
    unsigned long   Filler;
} __attribute__((packed));

_MyRequest request;
_MyAnswer  answer;

RemoteCmdServer::RemoteCmdServer(QObject * parent)
    : QTcpServer(parent)
{
    qDebug() << "Server started";

    listen(QHostAddress("172.31.250.110"), 5004);

    connect(this, SIGNAL(newConnection()), this, SLOT(processPendingRequest()));
}

void RemoteCmdServer::processPendingRequest()
{
    qDebug() << "Process request";

    QTcpSocket * clientConnection = nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));

    // get the request
    int ret = clientConnection->read((char*)&request, sizeof(request));
    qDebug() << "READ: " << ret;
    if(ret == sizeof(request))
    {
        // send answer
        clientConnection->write((char*)&answer, sizeof(answer));
    }

    qDebug() << "Disconnecting...";
    clientConnection->disconnectFromHost();
}   

如果我评论if(ret == sizeof(request))行,我就可以正确写作 然而,我无法从套接字读取(我总是得到0字节) 我100%确定我用来向我的应用程序发送数据包的TCP工具运行正常 这是我的应用程序的调试输出:

Server started     
Process request    
READ: 0     
Disconnecting...     

我做错了什么?请指教!

2 个答案:

答案 0 :(得分:1)

你试图从新连接中读取数据而不返回到Qt事件循环 - 我认为这不会起作用。

在您接受连接后...

QTcpSocket * clientConnection = nextPendingConnection();

您需要使用类似......

之类的信息连接到readyRead信号
connect(clientConnection, SIGNAL(readyRead()), this, SLOT(my_read_slot()));

其中my_read_slot是实际执行读操作的成员函数。

答案 1 :(得分:1)

您应该以非阻塞或阻止方式等待数据。您可以使用waitForReadyRead以阻止方式执行此操作。

trigger()
相关问题