QT 启动了一个线程,在线程中实现TCPScoket通信,但连接不到服务器了 30C

一、刚开始做的时候直接在主线程中测试了以下程序:
1.头文件

 class MainWindow : public QMainWindow
{
    Q_OBJECT
private slots:
    void on_pushButton_clicked();
    void connected();
    void readyread();
private:
    QTcpSocket *socket;
};
2.源文件
void MainWindow::on_pushButton_clicked()
{
    this->socket=new QTcpSocket();
    this->socket->connectToHost("10.10.15.11",26,QTcpSocket::ReadWrite);
    connect(this->socket,SIGNAL(connected()),this,SLOT(readyread()));
}
void MainWindow::connected()
{
    connect(this->socket,SIGNAL(readyRead()),this,SLOT(readyread()));
}
void MainWindow::readyread()
{
        QByteArray qba = socket->readAll();
}
这个时候是可以连接并接收到数据的。


二、现在需要在QT项目中启动一个线程,这个线程专门负责TCPScoket通信接收数据,程序如下:
1.头文件
class ThreadReceive : public QThread
{
    Q_OBJECT
private slots:
    void connected();
    void readyread();
public:
    void run();
private:
    QTcpSocket *ScoketRecv;
};
2.源文件
void ThreadReceive::run()
{
    this->ScoketRecv=new QTcpSocket();
    this->ScoketRecv->connectToHost("10.10.15.11",26,QTcpSocket::ReadWrite);
    connect(this->ScoketRecv,SIGNAL(connected()),this,SLOT(connected()));
}
void ThreadReceive::connected()
{
    connect(this->ScoketRecv,SIGNAL(readyRead()),this,SLOT(readyread()));
}
void ThreadReceive::readyread()
{
    QByteArray recvBuf=ScoketRecv->readAll();
}

在主线程中启动子线程之后会跳转到void ThreadReceive::run()函数中,但 connect(this->ScoketRecv,SIGNAL(connected()),this,SLOT(readyread()));一直连接不到,也就是跳不到void ThreadReceive::readyread()中。
麻烦大神看看是哪儿有问题,谢谢!

3个回答

我对比了一下,貌似这里错了:
void ThreadReceive::run()
{
this->ScoketRecv=new QTcpSocket();
this->ScoketRecv->connectToHost("10.10.15.11",26,QTcpSocket::ReadWrite);
connect(this->ScoketRecv,SIGNAL(connected()),this,SLOT(connected()));---》改成SLOT(readyread()));
}
void ThreadReceive::connected()
{
connect(this->ScoketRecv,SIGNAL(readyRead()),this,SLOT(readyread()));
}
void ThreadReceive::readyread()
{
QByteArray recvBuf=ScoketRecv->readAll();
}

排版略乱...................................................................

QTcpSocket多线程可能会出bug

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!