In #3 and #6 I already wrote that I've envolved QThread to get event loop, because it didn't work as I had Client Socket inherited from QObject. This was just suggestion that it doesn't work because of missing event loop. By the way, socket belongs to thread as it's instantiated in run() (see code above). As I wrote before, this all works also if I use this ClientSocket in my simple appplication from main(). But in Dll of project (plugin) I'm now working with, I have a problem that non blocking methods didn't get called whereas blocking methods work.
To avoid further confusions with threads I post version without QThread that behaves the same way.
class ClientSocket
: public QObject { Q_OBJECT
public:
connect(m_socket, SIGNAL(readyRead()), this, SLOT(test()));
}
virtual ~ClientSocket() {};
bool connectToHost
(QString host,
int port
) { m_socket->connectToHost(host, port);
return m_socket->waitForConnected(1000);
}
void write(const char* Data,unsigned int nBytes) {
{
m_socket->write(Data);
m_socket->flush();
m_socket->waitForBytesWritten();
//bool hasData=m_socket->waitForReadyRead();
//int num=m_socket->bytesAvailable();
//QByteArray data=m_socket->readAll();
//qDebug()<<num<<data;
}
}
public slots:
void test() { qDebug()<<"readyRead()"; }
private:
};
class ClientSocket : public QObject {
Q_OBJECT
public:
ClientSocket() : QObject()
, m_socket(new QTcpSocket(this)) {
connect(m_socket, SIGNAL(readyRead()), this, SLOT(test()));
}
virtual ~ClientSocket() {};
bool connectToHost(QString host, int port) {
m_socket->connectToHost(host, port);
return m_socket->waitForConnected(1000);
}
void write(const char* Data,unsigned int nBytes) {
if (m_socket && (m_socket->state() == QAbstractSocket::ConnectedState))
{
m_socket->write(Data);
m_socket->flush();
m_socket->waitForBytesWritten();
//bool hasData=m_socket->waitForReadyRead();
//int num=m_socket->bytesAvailable();
//QByteArray data=m_socket->readAll();
//qDebug()<<num<<data;
}
}
public slots:
void test() { qDebug()<<"readyRead()"; }
private:
QTcpSocket* m_socket;
};
To copy to clipboard, switch view to plain text mode
From DLL code it's used like this
SomeClass::SomeClass() : m_ClientSocket() {
bool bConnected = m_ClientSocket.connectToHost("localhost", 1000);
if (bConnected) m_ClientSocket.write("rtst", 4);
}
SomeClass::SomeClass() : m_ClientSocket() {
bool bConnected = m_ClientSocket.connectToHost("localhost", 1000);
if (bConnected) m_ClientSocket.write("rtst", 4);
}
To copy to clipboard, switch view to plain text mode
test() slot is not called. if I uncomment lines in write() I have expected response (num=4, data="rtst") and slot is called. But waitForReadyRead() shouldn't be called in order to get slot working...
Bookmarks