weixin_38354049
weixin_38354049
采纳率0%
2017-04-17 03:31

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

30

一、刚开始做的时候直接在主线程中测试了以下程序:
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条回答

  • baixuefeng1 90mark 4年前

    我对比了一下,貌似这里错了:
    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();
    }

    点赞 1 评论 复制链接分享
  • what951006 小乌龟在大乌龟背上 4年前

    QTcpSocket多线程可能会出bug

    点赞 评论 复制链接分享
  • luoyongweis luoyongweis 4年前

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

    点赞 评论 复制链接分享

相关推荐