Ali_Sayrex
Ali_Sayrex

Reputation: 1

Qtcp Sending Data in Custom Rate Between Server and Client

i have this project working on

a simple Server/Client App :

  1. Which Server sends Data ( some strings ...) in a Custom Rate (data/second) )

  2. Client Controls the rate (can changes the rate)

  3. Client calculate data rate which is sending by server and compare to submitted Rate

I made simple TCP Server Client Chat

here is the problem :

enter image description here

Server:

#include "widget.h"
#include "ui_widget.h"
#include <QtWidgets/QMessageBox>
#include <QTime>


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    ui->lineEdit_Port->setText("5003");
    ui->pushButton_Send->setEnabled(false);


    m_server = new QTcpServer();

    connect(m_server,&QTcpServer::newConnection,this,&Widget::server_New_Connect);

}

Widget::~Widget()
{
    m_server->close();
    m_server->deleteLater();
    delete ui;
}

 void Widget::server_New_Connect()
 {
     //Get client connection
    m_socket = m_server->nextPendingConnection();

    QObject::connect(m_socket,&QTcpSocket::readyRead,this,&Widget::socket_Recv_Data);
    QObject::connect(m_socket,&QTcpSocket::disconnected,this,&Widget::socket_Disconnect);

    ui->textBrowser->setTextColor(Qt::green);
    ui->textBrowser->setCurrentFont(QFont("Times New Roman",10));
    ui->textBrowser->append(tr("Client Connected!%1\n").arg(QTime::currentTime().toString()));
    ui->pushButton_Send->setEnabled(true);

 }

void Widget:: socket_Recv_Data()
{
    QByteArray data_tmp;
    data_tmp = m_socket->readAll();
    if(!data_tmp.isEmpty())
    {
        QString str = QString(data_tmp);

        ui->textBrowser->setTextColor(Qt::gray);
        ui->textBrowser->setCurrentFont(QFont("Times New Roman",10));
        ui->textBrowser->append("From Client:  "+QTime::currentTime().toString());

         ui->textBrowser->setTextColor(Qt::blue);
         ui->textBrowser->setCurrentFont(QFont("Times New Roman",13));
        ui->textBrowser->append(str);

        QTextCursor cursor = ui->textBrowser->textCursor(); //Automatically drop to the bottom
        cursor.movePosition(QTextCursor::End);
        ui->textBrowser->setTextCursor(cursor);
    }
}

void Widget:: socket_Disconnect()
{
    ui->pushButton_Send->setEnabled(false);
    ui->textBrowser->setTextColor(Qt::gray);
    ui->textBrowser->setCurrentFont(QFont("Times New Roman",10));
    ui->textBrowser->append(tr("Client Disconnected !%1\n").arg(QTime::currentTime().toString()));

}

void Widget::on_pushButton_Listen_clicked()
{
    if (ui->pushButton_Listen->text() ==QString("start server"))
        {
        qint16 port = ui->lineEdit_Port->text().toInt();

        if(!m_server->listen(QHostAddress::Any, port))
        {
            QMessageBox::critical(this,"Error!",m_server->errorString(),QMessageBox::Yes | QMessageBox::No,QMessageBox::Yes );
            return;

        }
        ui->pushButton_Listen->setText("stop server");

    }
    else
    {
        if(m_socket->state() == QAbstractSocket::ConnectedState)
        {
            m_socket->disconnectFromHost();
        }
        m_server->close();

        ui->pushButton_Listen->setText("start server");
        ui->pushButton_Send->setEnabled(false);
    }
}

void Widget::on_pushButton_Send_clicked()
{
    if (ui->textEdit->toPlainText() == QString())
    {
        QMessageBox msgb;
        msgb.setText("Cannot send empty message !");
        msgb.resize(60,40);
        msgb.exec();
        return;
    }
    m_socket->write(ui->textEdit->toPlainText().toUtf8());

    ui->textBrowser->setTextColor(Qt::gray);
    ui->textBrowser->setCurrentFont(QFont("Times New Roman",10));
    ui->textBrowser->append("From Server:  "+QTime::currentTime().toString());

     ui->textBrowser->setTextColor(Qt::red);
     ui->textBrowser->setCurrentFont(QFont("Times New Roman",16));
    ui->textBrowser->append(ui->textEdit->toPlainText().toUtf8());
    m_socket->flush();
    ui->textEdit->clear();


}

Client :

#include "widget.h"
#include "ui_widget.h"
#include <QtWidgets/QMessageBox>
#include <QTime>


Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_socket=new QTcpSocket();

    QObject::connect(m_socket,&QTcpSocket::readyRead,this,&Widget::sockt_recv_data);
    QObject::connect(m_socket,&QTcpSocket::disconnected,this,&Widget::socket_disconnect);

    ui->pushButton_Send->setShortcut(QKeySequence(tr("ctrl+return")));

    ui->lineEdit_IP->setText("127.0.0.1");
    ui->lineEdit_Port->setText("5003");
    ui->pushButton_Send->setEnabled(false);
}

Widget::~Widget()
{
    delete m_socket;
    delete ui;
}

void Widget::on_pushButton_Connect_clicked()    //Connect button
{
    QString IP;
    qint16 port;

    if (ui->pushButton_Connect->text() == QString("Connect"))
    {
        IP=ui->lineEdit_IP->text();
        port=ui->lineEdit_Port->text().toInt();

        m_socket->abort();
        m_socket->connectToHost(IP,port);

            if (!m_socket->waitForConnected())
                {

                    QMessageBox msgBox;
                     msgBox.setText("Connection timed out!");
                     msgBox.resize(40,30);
                     msgBox.exec();
                    return;
                }

         QMessageBox msgBox;
          msgBox.setText("Connection succeeded!");
          msgBox.resize(40,30);
          msgBox.exec();

        ui->pushButton_Send->setEnabled(true);
        ui->pushButton_Connect->setText("Disconnect");
       }
    else
    {
        m_socket->disconnectFromHost();
        ui->pushButton_Connect->setText("Connect");
        ui->pushButton_Send->setEnabled(false);
    }
}

void Widget::on_pushButton_Send_clicked()  //Send button
{
    if (ui->textEdit->toPlainText()== QString()) //Empty message detection
    {
        QMessageBox msgb;
        msgb.setText("Cannot send empty messages!");
        msgb.resize(60,40);
        msgb.exec();
        return;
    }
    ui->textBrowser->setTextColor(Qt::gray);
    ui->textBrowser->setCurrentFont(QFont("Times New Roman",10));
    ui->textBrowser->append("From Client:  "+QTime::currentTime().toString());

     ui->textBrowser->setTextColor(Qt::blue);
     ui->textBrowser->setCurrentFont(QFont("Times New Roman",16));
    ui->textBrowser->append(ui->textEdit->toPlainText().toUtf8());

    m_socket->write(ui->textEdit->toPlainText().toUtf8());
    m_socket->flush();
    ui->textEdit->clear();
}

void Widget:: sockt_recv_data()
{
    QByteArray data_tmp;
    data_tmp = m_socket->readAll();
    if (!data_tmp.isEmpty())
    {
        //QString str = ui->textBrowser->toPlainText();

        QString str=QString(data_tmp);

        ui->textBrowser->setTextColor(Qt::gray);
        ui->textBrowser->setCurrentFont(QFont("Times New Roman",10));
        ui->textBrowser->append("From Server:  "+QTime::currentTime().toString());

         ui->textBrowser->setTextColor(Qt::red);
         ui->textBrowser->setCurrentFont(QFont("Times New Roman",13));
        ui->textBrowser->append(str);



    }
}

void Widget:: socket_disconnect()
{
    ui->pushButton_Send->setEnabled(false);
    ui->pushButton_Connect->setText("Connect");
    QMessageBox msgBox;
     msgBox.setText("Disconnect");
     msgBox.resize(40,30);
     msgBox.exec();
}

Upvotes: 0

Views: 92

Answers (1)

Diego Desenvolvedor
Diego Desenvolvedor

Reputation: 388

You can try something like this:

Here I send using a QJsonDocument, I think is easier to manipulate. The function send the exact size of the array. I something goes wrong, the write_socket_retry is called to try again.

void multisocket::write_socket(const QJsonObject &obj)
{    

    QJsonDocument doc(obj);
    QByteArray array(doc.toJson());

    qint32 size = array.size();
    QByteArray total = IntToArray(size);

    socket->write(total);
    qint64 writed = socket->write(array); 

    if(writed == size){

        QString str = QString("Socket sent packet: %3 size  %1 - Socket descriptor: %2")
                .arg(QString::number(size))
                .arg(QString::number(socket->socketDescriptor()))
                .arg(writed > 0);

        qDebug() << str;

        total_sent = 0;

    } else {

        socket->abort();

        QTimer::singleShot(3000, [this, obj](){            
            write_socket_retry(obj);
        });
    }


}

void multisocket::write_socket_retry(const QJsonObject &obj){

    if(total_sent >= 10){

        QString str = QString("Socket fail  - Socket descriptor: %1 ")
                .arg(QString::number(socket->socketDescriptor()));


        qDebug() << str;
        total_sent = 0;


    } else {

        QString str = QString("Socket fail - Socket descriptor: %1 ")
                .arg(QString::number(socket->socketDescriptor()));


        qDebug() << str;

        total_sent++;
        write_socket(obj);
    }

}

Upvotes: 0

Related Questions