I have worked through C++ Qt 68 - QTcpServer using multiple threads
and followed his steps, but I can't seem to get the program to work correctly.
I am using Qt 6.3.0 and the only difference between VoidRealm's code and mine is that I am using the new Signals and Slots
system.
My Code:
//myserver.h
#ifndef MYSERVER_H
#define MYSERVER_H
#include <QTcpServer>
#include <QObject>
#include <QDebug>
#include "mythread.h"
class MyServer : public QTcpServer
{
Q_OBJECT
public:
explicit MyServer(QObject *parent = nullptr);
void startServer();
protected:
void incomingConnection(int socketDescriptor);
};
#endif // MYSERVER_H
//myserver.cpp
#include "myserver.h"
MyServer::MyServer(QObject *parent)
: QTcpServer{parent}
{
}
void MyServer::startServer()
{
if(!this->listen(QHostAddress::Any, 1234))
{
qDebug() << "Could not start Server!";
}
else
{
qDebug() << "Listening...";
}
}
void MyServer::incomingConnection(int socketDescriptor)
{
qDebug() << socketDescriptor << " Connectng...";
MyThread *thread = new MyThread(socketDescriptor, this);
connect(thread, &QThread::finished, thread, &QObject::deleteLater);
thread->start();
}
//mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QObject>
#include <QTcpSocket>
#include <QDebug>
class MyThread : public QThread
{
Q_OBJECT
public:
MyThread(int ID, QObject *parent = nullptr);
void run();
void readyRead();
void disconnected();
signals:
void error(QTcpSocket::SocketError socketError);
private:
QTcpSocket *socket;
int socketDescriptor;
};
#endif // MYTHREAD_H
//mythread.cpp
#include "mythread.h"
MyThread::MyThread(int ID, QObject *parent)
:QThread(parent)
{
this->socketDescriptor = ID;
}
void MyThread::run()
{
qDebug() <<socketDescriptor << " Starting Thread";
socket = new QTcpSocket();
if(!socket->setSocketDescriptor(this->socketDescriptor))
{
emit error(socket->error());
return;
}
connect(socket, &QIODevice::readyRead, this, &MyThread::readyRead,Qt::DirectConnection);
connect(socket, &QTcpSocket::disconnected, this, &MyThread::disconnected,Qt::DirectConnection);
qDebug() << socketDescriptor << " Client Connected!";
exec();
}
void MyThread::readyRead()
{
QByteArray Data = socket->readAll();
qDebug() << socketDescriptor << " Data in: " << Data;
socket->write(Data);
}
void MyThread::disconnected()
{
qDebug() << socketDescriptor << " Disconnected";
socket->deleteLater();
quit();
}
When Running this, I get the console saying Listening...
, but when I then use command prompt and change it to telnet using ...> telnet
, and then type ...> open 127.0.0.1 1234
, all I am getting is:
Welcome to Microsoft Telnet Client
Escape Character is 'CTRL+]'
Microsoft Telnet> open 127.0.0.1 1234
Connecting To 127.0.0.1...
After which nothing happens. What exactly am I doing wrong?
I found my problem. The int
in the incomingConnection(int socketDescriptor)
should have been a qintptr
, making it incomingConnection(qintptr socketDescriptor)
The program works now.