简体   繁体   English

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

[英]Qt QTcpSocket doesn't emit signal when reading data

I need to update the content of a chat window when it receives a message. 接收消息时,我需要更新聊天窗口的内容。 Here are the two functions I use : 这是我使用的两个功能:

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();
}

This is the slot that is called when the socket has something to read. 这是套接字读取某些内容时调用的插槽。 It works fine, except the signal either isn't emitted or the connected slot isn't called. 它工作正常,除了不发出信号或不调用连接的插槽。

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() << "]";
    }
}

Console output : 控制台输出:

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

Now, if I do this, it goes into an infinite loop but suddenly the signal/slot thing works just fine and my text gets sent to the chat window and displayed : 现在,如果执行此操作,它将陷入无限循环,但是突然之间,信号/插槽功能运行正常,并且我的文本被发送到聊天窗口并显示:

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() << "]";
    }
}

Console output : 控制台输出:

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

I don't understand why it doesn't work in the first place or why, when I turn it into an infinite loop, it suddenly starts working... 我不明白为什么它一开始就不起作用,或者为什么当我将其变成无限循环时,它突然开始起作用...

PS : Here is the updateChat slot : PS:这是updateChat插槽:

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

How do you perform socket connection? 您如何执行套接字连接? I cant get code responsible for listening for connection. 我无法获得负责监听连接的代码。 If you dont have any other tcp client try with telnet 如果您没有其他任何TCP客户端,请尝试使用telnet

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

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