My client setup is as follows: The client first sends a packet which contains the length of the actual data to be read from the socket. The client then sends the actual data itself. ( I am pre-pending the data packet length before I actually send the data).
I want to know how can I read the next packet in Qt Creator. I get an error saying No such slot found: MyThread::readPacket (int). What am I doing wrong ?
(Ignore the part if I am reading the wrong number of bytes)
My server side code is as Follows:
#include "thread.h"
#include <QDebug>
#include "DataSetProtos.pb.h"
MyThread::MyThread(qintptr ID, QObject *parent) :
QThread(parent)
{
this->socketDescriptor = ID;
}
void MyThread::run()
{
// thread starts here
qDebug() << " Thread started";
socket = new QTcpSocket();
// set the ID
if(!socket->setSocketDescriptor(this->socketDescriptor))
{
// something's wrong, we just emit a signal
emit error(socket->error());
return;
}
// connect socket and signal
// note - Qt::DirectConnection is used because it's multithreaded
// This makes the slot to be invoked immediately, when the signal is emitted.
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
// We'll have multiple clients, we want to know which is which
qDebug() << socketDescriptor << " Client connected";
// make this thread a loop,
// thread will stay alive so that signal/slot to function properly
// not dropped out in the middle when thread dies
exec();
}
void MyThread::readyRead()
{
// get the information
char* buffer = new char[SIZE];
int iResult= socket->read(buffer, SIZE);
connect(socket,SIGNAL(readyRead()), this, SLOT(readPacket(iResult)), Qt::DirectConnection);
}
void MyThread::readPacket(int bufferLength)
{
char *buffer = new char[bufferLength];
int iResult = socket->read(buffer, bufferLength);
printf("\n Read 2 : %d", iResult);
}
void MyThread::Print(Visualization::PacketData packet)
{
printf("\n\nPacket Name : %s", packet.name());
printf("\n Packet length : %d ", packet.length());
}
void MyThread::disconnected()
{
qDebug() << socketDescriptor << " Disconnected";
socket->deleteLater();
exit(0);
}
My thread.h file is as follows:
#ifndef THREAD_H
#define THREAD_H
#include <QThread>
#include <QTcpSocket>
#include <QDebug>
#include "DataSetProtos.pb.h"
#define SIZE 500
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(qintptr ID, QObject *parent = 0);
void run();
signals:
void error(QTcpSocket::SocketError socketerror);
public slots:
void readyRead();
void readPacket( int bufferLength);
void disconnected();
void Print( Visualization::PacketData packet );
private:
QTcpSocket *socket;
qintptr socketDescriptor;
};
#endif // THREAD_H