繁体   English   中英

Qtcp在服务器和客户端之间以自定义速率发送数据

[英]Qtcp Sending Data in Custom Rate Between Server and Client

我有这个项目正在进行中

一个简单的服务器/客户端应用程序:

  1. 哪个服务器以自定义速率(数据/秒)发送数据(一些字符串......)

  2. 客户控制费率(可以更改费率)

  3. 客户端计算服务器发送的数据速率并与提交的速率进行比较

我做了简单的 TCP 服务器客户端聊天

这是问题所在:

  • 如何以自定义速率发送数据? 比如:一秒100个字符串,一秒100个单词……

  • 应该如何让服务器知道速率变化?

  • 客户如何计算费率?

在此处输入图像描述

服务器:

#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();


}

客户:

#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();
}

你可以尝试这样的事情:

这里我使用一个QJsonDocument 发送,我认为更容易操作。 function 发送数组的确切大小。 我出了点问题,调用write_socket_retry重试。

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);
    }

}
①如果本文未解决您的问题,请点击查看与本文相关的问题
②如果本文未解决您的问题,请向程序员专用AI小助手提问
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM