gpt4 book ai didi

multithreading - QThread中的QTcpSocket

转载 作者:行者123 更新时间:2023-12-03 13:18:09 24 4
gpt4 key购买 nike

我有简单的服务器连接线程。当您调用函数receiveString时,它将失败。但是,当您在run()中执行相同的代码时,它将成功。函数receiveString需要什么?

我都尝试过

bool TestServerThread::receiveString(QTcpSocket& sock, QString& str)
bool TestServerThread::receiveString(QTcpSocket* sock, QString& str)

实际代码:
TestServerThread::TestServerThread(int socketDescriptor, QObject *parent) : QThread(parent), socketDescriptor(socketDescriptor)
{
}


bool TestServerThread::receiveString(QTcpSocket& sock, QString& str)
{
if(sock.isValid())
{
if(!sock.waitForReadyRead(30))
{
qWarning() << "fail"; // fails here
return false;
}
QByteArray buf = sock.readAll();
str = buf;
}
}

void TestServerThread::run()
{
QTcpSocket sock;
if (!sock.setSocketDescriptor(socketDescriptor)) {
emit error(sock.error());
return;
}

bool ok = true;
while(ok)
{
QString str;
//if(ok) ok = receiveString(sock, str);

if(!sock.waitForReadyRead(30))
{
qWarning() << "false";
}
QByteArray buf = sock.readAll(); // same routine succeeds
str = buf;
qWarning() << str;

qWarning() << "Received: " << str;
if(ok) ok = sendString(sock, "kaka");
}
sock.disconnectFromHost();
sock.waitForDisconnected();
}

最佳答案

您的代码破坏了进程堆栈,或者超时值不够。

关于multithreading - QThread中的QTcpSocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1543582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com