1
I created a server in QT Creator, and also implemented the Threads service in it. But when I connect to the server, with the application "Client" and send a data, the server does not receive ... He should receive and print the received data, but this is not happening... I’ll post the server code here, if anyone knows how to fix thank you!
Note: I already did a test with the client, sending data to a server without the threading service, and the server received it. That is, the client is working normally... I believe something is wrong with the threads on this server.
mythread. h
#ifndef THREAD_H
#define THREAD_H
#include <QThread>
#include <QTcpSocket>
#include <QTcpServer>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(int ID, QObject *parent = 0);
void run();
signals:
void error(QTcpSocket::SocketError socketerror);
public slots:
void readyRead();
void disconnected();
private:
QTcpSocket *socket;
int socketDescriptor;
};
#endif // THREAD_H
mythread. c
#include "mythread.h"
MyThread::MyThread(int ID, QObject *parent) : QThread(parent)
{
this->socketDescriptor = ID;
}
void MyThread::run() {
qDebug() << "Starting thread";
socket = new QTcpSocket();
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::DirectConnection);
if(!socket->setSocketDescriptor(this->socketDescriptor)) {
emit error(socket->error());
return;
}
qDebug() << "Client connected";
}
void MyThread::readyRead() {
QByteArray data = socket->readAll();
qDebug()<< data;
socket->write(data);
}
void MyThread::disconnected() {
qDebug() << socketDescriptor << " Disconnected";
socket->deleteLater();
exit(0);
}
server. c
#include "server.h"
Server::Server(QObject *parent) : QTcpServer(parent)
{
}
void Server::StartServer() {
if(!this->listen(QHostAddress::Any, 10000)) {
qDebug() << "Could not start server";
} else {
qDebug() << "Listening...";
}
}
void Server::incomingConnection(int socketDescriptor) {
qDebug() << socketDescriptor << " Connecting...";
MyThread *thread = new MyThread(socketDescriptor, this);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
server. h
#ifndef SERVER_H
#define SERVER_H
#include <QTcpServer>
#include <QDebug>
#include "mythread.h"
class Server : public QTcpServer
{
Q_OBJECT
public:
explicit Server(QObject *parent = 0);
void StartServer();
signals:
public slots:
protected:
void incomingConnection(int socketDescriptor);
};
#endif // SERVER_H
main. c
#include <QCoreApplication>
#include "server.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Server server;
server.StartServer();
return a.exec();
}
Resolved :D, thank you!!!
– Vynstus