用qt写一个tcp服务器与客户端之间如何计算延时率的示例
时间: 2024-02-24 16:59:44 浏览: 123
以下是一个简单的示例,演示如何使用Qt编写TCP服务器和客户端,并计算延迟率。
服务端(server.cpp):
```cpp
#include <QTcpServer>
#include <QTcpSocket>
#include <QDateTime>
class Server : public QTcpServer
{
Q_OBJECT
public:
explicit Server(QObject *parent = nullptr) : QTcpServer(parent) {}
protected:
void incomingConnection(qintptr socketDescriptor) override
{
QTcpSocket *socket = new QTcpSocket(this);
if (socket->setSocketDescriptor(socketDescriptor))
{
connect(socket, &QTcpSocket::readyRead, this, &Server::onReadyRead);
connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater);
m_clients.append(socket);
}
else
{
delete socket;
}
}
signals:
void latencyCalculated(qint64);
private slots:
void onReadyRead()
{
QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
if (socket)
{
QByteArray request = socket->readAll();
if (request == "ping")
{
qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
socket->write("pong");
socket->flush();
qint64 latency = QDateTime::currentMSecsSinceEpoch() - timestamp;
emit latencyCalculated(latency);
}
}
}
private:
QList<QTcpSocket*> m_clients;
};
```
客户端(client.cpp):
```cpp
#include <QTcpSocket>
#include <QDateTime>
class Client : public QObject
{
Q_OBJECT
public:
explicit Client(QObject *parent = nullptr) : QObject(parent) {}
void connectToServer(const QString &host, quint16 port)
{
m_socket.connectToHost(host, port);
connect(&m_socket, &QTcpSocket::connected, this, &Client::onConnected);
connect(&m_socket, &QTcpSocket::disconnected, this, &Client::onDisconnected);
connect(&m_socket, &QTcpSocket::readyRead, this, &Client::onReadyRead);
}
signals:
void latencyCalculated(qint64);
private slots:
void onConnected()
{
m_socket.write("ping");
m_socket.flush();
m_timestamp = QDateTime::currentMSecsSinceEpoch();
}
void onDisconnected()
{
m_socket.deleteLater();
}
void onReadyRead()
{
QByteArray response = m_socket.readAll();
if (response == "pong")
{
qint64 latency = QDateTime::currentMSecsSinceEpoch() - m_timestamp;
emit latencyCalculated(latency);
}
}
private:
QTcpSocket m_socket;
qint64 m_timestamp;
};
```
主函数(main.cpp):
```cpp
#include <QCoreApplication>
#include "server.h"
#include "client.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Server server;
QObject::connect(&server, &Server::latencyCalculated, [&](qint64 latency) {
qDebug() << "Server latency:" << latency << "ms";
});
server.listen(QHostAddress::Any, 12345);
Client client;
QObject::connect(&client, &Client::latencyCalculated, [&](qint64 latency) {
qDebug() << "Client latency:" << latency << "ms";
});
client.connectToServer("localhost", 12345);
return a.exec();
}
```
上述代码演示了一个TCP服务器和客户端之间的简单通信,并计算了延迟率。当客户端连接到服务器时,客户端会发送一个"ping"请求,服务器收到请求后会记录时间戳并发送一个"pong"响应,客户端收到响应后也会记录时间戳并计算延迟率。服务器和客户端的延迟率分别通过信号和槽进行传递和处理。
阅读全文