succulent_lily
26th November 2008, 09:25
I establish a multi-thread server,but encouter some problems,after declare tcpsocket in thread::run,I want to operate the tcpsocket in slot ,such as write or read,but i couldnot.
how to resolve this problem,forgive my poor english,3x
the thread.h as follows
class FortuneThread : public QThread
{
Q_OBJECT
public:
FortuneThread(int socketDescriptor, QObject *parent);
void run();
signals:
void error(QTcpSocket::SocketError socketError);
void toserver(const QString info);
private:
int socketDescriptor;
QTcpSocket *tcpSocket;
bool stopped;
private slots:
void recfserver(const QString peeradd);
};
the thread.cpp as follows
FortuneThread::FortuneThread(int socketDescriptor, const QString &fortune,
QObject *parent)
: QThread(parent), socketDescriptor(socketDescriptor)
{
};
void FortuneThread::run()
{
tcpSocket = new QTcpSocket();
if (!((*tcpSocket).setSocketDescriptor(socketDescript or))) {
emit error((*tcpSocket).error());
return;
}
(*tcpSocket).waitForDisconnected();
}
void FortuneThread::recfserver(const QString peeradd)
{
QString text=tr("transfer success!");
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint16)0;
out << text;
(*tcpSocket).write(block);
};
when i debug,the error as follows
QObject cannot create children for a parent that is in a different thread.
(parent is QNativeSocketEngine,parent's thread is FortuneThread,current thread
is QThread)
how to resolve this problem,forgive my poor english,3x
the thread.h as follows
class FortuneThread : public QThread
{
Q_OBJECT
public:
FortuneThread(int socketDescriptor, QObject *parent);
void run();
signals:
void error(QTcpSocket::SocketError socketError);
void toserver(const QString info);
private:
int socketDescriptor;
QTcpSocket *tcpSocket;
bool stopped;
private slots:
void recfserver(const QString peeradd);
};
the thread.cpp as follows
FortuneThread::FortuneThread(int socketDescriptor, const QString &fortune,
QObject *parent)
: QThread(parent), socketDescriptor(socketDescriptor)
{
};
void FortuneThread::run()
{
tcpSocket = new QTcpSocket();
if (!((*tcpSocket).setSocketDescriptor(socketDescript or))) {
emit error((*tcpSocket).error());
return;
}
(*tcpSocket).waitForDisconnected();
}
void FortuneThread::recfserver(const QString peeradd)
{
QString text=tr("transfer success!");
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint16)0;
out << text;
(*tcpSocket).write(block);
};
when i debug,the error as follows
QObject cannot create children for a parent that is in a different thread.
(parent is QNativeSocketEngine,parent's thread is FortuneThread,current thread
is QThread)