Hi,
I have a multithread application with 1 server and multiple client.
This is my QTCode:
#ifndef MESSAGETHREAD_H
#define MESSAGETHREAD_H
#include <QThread>
#include <QTcpSocket>
#include <QTcpServer>
class MessageThread
: public QThread{
Q_OBJECT
public:
MessageThread();
void run();
public slots:
void newMessConnection();
signals:
private:
};
#endif
#ifndef MESSAGETHREAD_H
#define MESSAGETHREAD_H
#include <QThread>
#include <QTcpSocket>
#include <QTcpServer>
class MessageThread : public QThread
{
Q_OBJECT
public:
MessageThread();
void run();
public slots:
void newMessConnection();
signals:
void error(QTcpSocket::SocketError socketError);
private:
QTcpServer* messageSrv;
QString text;
};
#endif
To copy to clipboard, switch view to plain text mode
Implementation:
#include "MessageThread.h"
#include <QtNetwork>
#define IPADDRESS "192.168.1.160"
MessageThread::MessageThread()
{
}
void MessageThread::run()
{
messageSrv = messageServer;
connect(messageServer, SIGNAL(newConnection()), this, SLOT(newMessConnection()));
quint16 port;
xIpAddress.setAddress(IPADDRESS);
port = 2223;
if(!messageServer->listen(xIpAddress, port))
{
printf("\n Communication Manager.d: Unable to start the server.");
messageServer->close();
}
if (messageServer->isListening())
{
printf("\n Message Server initialized");
}
exec();
}
void MessageThread::newMessConnection()
{
printf("\n Message server: send data....");
QTcpSocket* connection
= messageSrv
->nextPendingConnection
();
out << (quint16)0;
out << test;
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));
connection->write(block);
}
#include "MessageThread.h"
#include <QtNetwork>
#define IPADDRESS "192.168.1.160"
MessageThread::MessageThread()
{
}
void MessageThread::run()
{
QTcpServer* messageServer = new QTcpServer;
messageSrv = messageServer;
connect(messageServer, SIGNAL(newConnection()), this, SLOT(newMessConnection()));
QHostAddress xIpAddress;
quint16 port;
xIpAddress.setAddress(IPADDRESS);
port = 2223;
if(!messageServer->listen(xIpAddress, port))
{
printf("\n Communication Manager.d: Unable to start the server.");
messageServer->close();
}
if (messageServer->isListening())
{
printf("\n Message Server initialized");
}
exec();
}
void MessageThread::newMessConnection()
{
printf("\n Message server: send data....");
QTcpSocket* connection = messageSrv->nextPendingConnection();
QString test = "test data";
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint16)0;
out << test;
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));
connection->write(block);
}
To copy to clipboard, switch view to plain text mode
When I create this thread the line "connection->write(block);" show me this error:
QObject: Cannot create children for a parent that is in a different thread.
Parent's thread is MessageThread, current thread is QThread.
How i can solve it?
Can anyone help me please?
Bye
Bookmarks