Qt QTcpSocket在读取数据时不发出信号
Qt QTcpSocket doesn't emit signal when reading data
我需要在收到消息时更新聊天窗口的内容。下面是我使用的两个函数:
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
相关文章:
- 在 C++17 中,是否未定义使用无锁原子学保护从信号处理程序传递的数据?
- 通过信号槽发送QPixmap指针,空像素图数据
- 使用信号处理程序处理从 FIFO 接收的数据
- C++ QTextDocument::contentChange() 信号提供无效的输入数据
- QTcpSocket ready读取信号在传输数据时停止发出
- 无法获取数据槽中的发送方对象QAbstractItemModel的信号已更改
- 为什么我的数据无法在信号/插槽的表格之间传输
- 将数据馈送到数字信号中时会扭曲声音
- 如何通过信号和插槽发送数据
- Udp 在 QT 定时器信号中写入数据报
- 实时绘图的信号处理数据(c++中的FFT和GNUPLOT)
- 是否有任何本机 gtkmm 类可以从小部件的信号处理程序函数中排队命令/数据
- Qt数据改变信号-不使用提供的小区范围
- 我如何在缓冲区中分离信号数据
- 如何为所有qlineedit设置onclick信号以打开键盘小部件并发回数据
- 当从c++发出的信号向QML发送数据时
- 如何将Qt信号/槽名存储到数据结构中
- 在信号处理程序中使用长数据
- Qt QTcpSocket在读取数据时不发出信号
- QtSerialPort:readAll不会产生所有数据,也没有新的readyRead信号