Qt QTcpSocket在读取数据时不发出信号

Qt QTcpSocket doesn't emit signal when reading data

本文关键字:信号 数据 QTcpSocket 读取 Qt      更新时间:2023-10-16

我需要在收到消息时更新聊天窗口的内容。下面是我使用的两个函数:

void LinPop::_createChat(Client *socket)
{
    ChatDialog *chat = new ChatDialog();
    chat->setAttribute(Qt::WA_DeleteOnClose);
    qDebug() << "Connecting chat : ";
    qDebug() << connect(chat, SIGNAL(toSend(QString&)), socket, SLOT(send(QString&)));
    qDebug() << connect(socket, SIGNAL(gotTexted(QString)), chat, SLOT(updateChat(QString)));
    chat->exec();
}

这是当套接字有东西要读时调用的插槽。它工作得很好,除了信号没有发出或连接的插槽没有被调用。

void Client::readyRead()
{
    if (this->_socket->bytesAvailable() > 0)
    {
        QByteArray data = this->_socket->readAll();
        QString text(data);
        emit gotTexted(text);
        qDebug() << "ReadyRead [" << text << "] [" << this->_socket->bytesAvailable() << "]";
    }
}

控制台输出:

Connecting chat :  
true 
true 
Sent [ "Test" ] 
ReadyRead [ "Test" ] [ 0 ] 

现在,如果我这样做,它会进入一个无限循环但突然信号/槽的东西工作正常我的文本被发送到聊天窗口并显示:

void Client::readyRead()
{
    if (this->_socket->bytesAvailable() > 0)
    {
        QByteArray data = this->_socket->readAll();
        QString text(data);
        this->_socket->write(data); // Added this
        emit gotTexted(text);
        qDebug() << "ReadyRead [" << text << "] [" << this->_socket->bytesAvailable() << "]";
    }
}

控制台输出:

Connecting chat :  
true 
true 
Sent [ "Test" ] 
ReadyRead [ "Test" ] [ 0 ] 
Update Chat [ "Test" ] 
ReadyRead [ "Test" ] [ 0 ]
// Infinite Loop

我不明白为什么它一开始就不起作用,或者为什么当我把它变成一个无限循环时,它突然开始工作了…

PS:这是updateChat插槽:

void ChatDialog::updateChat(QString text)
{
    this->ui->tbConv->insertPlainText(text);
    qDebug() << "Update Chat [" << text << "]";
}

如何执行套接字连接?我不能得到负责监听连接的代码。如果您没有任何其他tcp客户端,请尝试telnet