首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > QT开发 >

Qt在多线程中使用QTcpSocket碰见的有关问题

2012-03-11 
Qt在多线程中使用QTcpSocket碰见的问题在Qt中写多线程网络通信时碰到了个问题,具体情形如下:新建一个FileR

Qt在多线程中使用QTcpSocket碰见的问题
在Qt中写多线程网络通信时碰到了个问题,具体情形如下:
新建一个FileRecvThread继承QThread,重写run函数

C/C++ code
class FileRecvThread : public QThread{    Q_OBJECTpublic:    explicit FileRecvThread(QObject *parent = 0);    FileRecvThread(quint32, QObject *parent = 0);    ~FileRecvThread();    void initSignalSlots();    void setPort(quint32 port);    quint32 getPort();     void dealShackHand(QByteArray *);    void replyExpectShackHand();protected:    void run();private:    quint32 port;    QTcpServer *pTcpServer;    QTcpSocket *pTcpSocket;public slots:    void startTcpServer();    void dealNewConnection();    void dealDatagram();FileRecvThread::FileRecvThread(quint32 port, QObject *parent) :    QThread(parent){    this->port = port;}void FileRecvThread::startTcpServer(){    if (!this->pTcpServer)    {        this->pTcpServer = new QTcpServer;        this->pTcpServer->listen(QHostAddress::Any, this->port);    }    else    {        this->pTcpServer->listen(QHostAddress::Any, this->port);    }}void FileRecvThread::run(){    this->startTcpServer();    this->initSignalSlots();    this->exec();}void FileRecvThread::initSignalSlots(){    connect(this->pTcpServer, SIGNAL(newConnection()), this, SLOT(dealNewConnection()));}void FileRecvThread::dealNewConnection(){    this->pTcpSocket = this->pTcpServer->nextPendingConnection();    connect(this->pTcpSocket, SIGNAL(readyRead()), this, SLOT(dealDatagram()));}void FileRecvThread::dealDatagram(){    QByteArray byteArray = this->pTcpSocket->readAll();    //这里出现问题    [color=#FF0000]this->pTcpSocket->write(QByteArray("deal"));[/color]}

原来写过java所以this用的比较多,大家见谅-。-!
把代码裁剪了下,一些不需要贴出来的都删掉了,具体问题如下:
在Qt creator下出现
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QNativeSocketEngine(0xac00878), parent's thread is FileRecvThread(0xac131b8), current thread is QThread(0x3e54c8),
意思我明白,就是对象不在同一线程下新建和调用出现的问题,可是
QTcpSocket作为FileRecvThread的子对象存在,而且用qDebug打印了下
pTcpSocket->thread()和pTcpServer->thread()这是一致的,都是0x3e54c8,
this->pTcpSocket->write("deal");也是在FileRecvThread内,按道理说他是属于FileRecvThread线程的,何况先使用了this->pTcpSocket->readAll();
能读取数据,而this->pTcpSocket->write();却不行,这是什么原因,求解
。。。。。
谢谢大虾了~~~

[解决办法]
connect后执行的槽函数并不是在你的run函数所处的线程中执行的
每次有信号其实都在主线程中执行,而你的QTcpSocket初始化是在run的线程中
不知道是不是这个原因

热点排行