Trying simple chat example with threading
-
as the title said i'm trying a simple chat console application using threads and QTcpServer
everything is working fine but the problem is that the server is (echo server) sends the data back
i want when a client send msg every other client receives it too
and like that its a chat app
here is the code
Server :@#include "myserver.h"
MyServer::MyServer(QObject *parent) :
QTcpServer(parent)
{
}void MyServer::start()
{
if (!this->listen(QHostAddress::AnyIPv4,1234))
{
qDebug () << "Error starting server " ;
}
else
{
qDebug () << "server started" ;}
}
void MyServer::incomingConnection(qintptr socketDescriptor)
{
qDebug() << socketDescriptor <<"Connected";
MyThread *thread = new MyThread(socketDescriptor,this);
connect(thread,SIGNAL(finished()),thread,SLOT(deleteLater()));
thread->start();
}
@thread:
@#include "mythread.h"
MyThread::MyThread(int id, QObject *parent) :
QThread(parent)
{
socketdescriptor = id;
}void MyThread::run()
{
qDebug () << socketdescriptor <<" Started";
socket = new QTcpSocket;
if (!socket->setSocketDescriptor(socketdescriptor))
{
emit socket->error();
return;
}
connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()),Qt::DirectConnection);
connect(socket,SIGNAL(disconnected()),this,SLOT(disconnected()),Qt::DirectConnection);
qDebug () <<socketdescriptor << "Connected";
exec();}
void MyThread::readyRead()
{
QByteArray datain ;
if (socket->canReadLine())
{
datain = socket->readAll();
qDebug() << datain;
dataout = "\nrecieved\n";} QByteArray dataout; socket->write(dataout);
}
void MyThread::disconnected()
{
qDebug () <<socketdescriptor<< "Disconnected";
socket->deleteLater();
exit(0);
}
@
at first i tried signals and slots
so thread sends a signal holding the msg to server
and the server sends it back to thread and like that all threads can receive it but i failed
but then someone told me to use QList (i didn't understand how to do this ) -
Hi and welcome to devnet,
He probably meant that you should keep a QList of your current connections so you can propagate the messages received to all of them.
-
hmmm interresting
is it wrong to subclass from QTcpServer or QThread ?! -
Yes it is. You can't inherit from two classes that are QObject. Furthermore, it wouldn't make sense in this case.
Before considering threading, you should start by getting a good understanding of how QTcpServer works.