0

我正在尝试将一些数据从 QLocalSocket 循环发送到 QLocalSever。服务器只获取第一个数据而不接收后续数据,但是如果我在客户端的每次调用之间引入 1 mec 延迟,则服务器开始接收所有内容。请查看以下客户端和服务器代码。

客户端.cpp

#include "client.h"
#include "QDataStream"
#include <QTest>

TestClient::TestClient() : m_socket{new QLocalSocket(this)}{
    m_socket->connectToServer("TestServer");
    if (m_socket->waitForConnected(1000)) {
      qDebug("socket Connected!");
    }
    connect(m_socket, &QLocalSocket::readyRead, this, &TestClient::onNewData);
}

void TestClient::onNewData() {
    qCritical() << "data received from server";
}

void TestClient::sendDataToServer() {
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_5_10);
    QString testString = "test data";
    out << quint32(testString.size());
    out << testString;
    m_socket->write(block);
    m_socket->flush();
}

void TestClient::startClient() {
    for(int i = 0; i < 5; i++) {
        //QTest::qWait(1); //works if I uncomment this line
        sendDataToServer();
    }
}

服务器.cpp

#include "server.h"

TestServer::TestServer() : m_server{new QLocalServer(this)} {
    QLocalServer::removeServer("TestServer");
    if (!m_server->listen("TestServer")) {
        qCritical() << "couldn't connect to server";
    }
    connect(m_server, &QLocalServer::newConnection, this, &TestServer::onNewConnection);
}

void TestServer::onNewConnection() {
    m_socket = m_server->nextPendingConnection();
    connect(m_socket, &QLocalSocket::readyRead, this,
            &TestServer::onNewData);
    connect(m_socket, &QLocalSocket::disconnected, m_socket,
            &QLocalSocket::deleteLater);
}

void TestServer::onNewData() {
    QLocalSocket* client = qobject_cast<QLocalSocket*>(sender());
    client->readAll();
    qCritical() << "data read by server";
}

来自 qt doc,据说

readyRead() 不会递归发出;如果您重新进入事件循环或在连接到 readyRead() 信号的插槽内调用 waitForReadyRead(),则不会重新发送该信号(尽管 waitForReadyRead() 仍可能返回 true)。

这是我的问题吗?添加计时器是这里唯一的解决方案吗?

你可以编译这个测试项目-> http://www.filedropper.com/testsocket

4

0 回答 0