QT tcp客户端循环发送数据
时间: 2023-08-23 17:04:42 浏览: 198
以下是一个简单的 QT tcp 客户端循环发送数据的示例代码:
```cpp
#include <QTcpSocket>
#include <QTimer>
class TcpClient : public QObject {
Q_OBJECT
public:
explicit TcpClient(QObject *parent = nullptr)
: QObject(parent), m_socket(new QTcpSocket(this)) {
connect(m_socket, &QTcpSocket::connected, this, &TcpClient::onConnected);
connect(m_socket, &QTcpSocket::disconnected, this, &TcpClient::onDisconnected);
connect(m_socket, &QTcpSocket::readyRead, this, &TcpClient::onReadyRead);
connect(m_socket, static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error),
this, &TcpClient::onError);
m_timer.setInterval(1000); // 发送数据的间隔
connect(&m_timer, &QTimer::timeout, this, &TcpClient::sendData);
}
void connectToHost(const QString &host, quint16 port) {
m_socket->connectToHost(host, port);
}
private slots:
void onConnected() {
qDebug() << "connected to server";
m_timer.start(); // 连接成功后启动定时器发送数据
}
void onDisconnected() {
qDebug() << "disconnected from server";
m_timer.stop(); // 断开连接后停止定时器
}
void onReadyRead() {
qDebug() << "received data from server:" << m_socket->readAll();
}
void onError(QAbstractSocket::SocketError error) {
qDebug() << "socket error:" << error;
}
void sendData() {
QByteArray data("hello");
qint64 bytesWritten = m_socket->write(data); // 发送数据
qDebug() << "sent data to server:" << data << ", bytesWritten:" << bytesWritten;
}
private:
QTcpSocket *m_socket;
QTimer m_timer;
};
```
使用示例:
```cpp
TcpClient client;
client.connectToHost("127.0.0.1", 8888);
```
注意:这里的 sendData 函数是在定时器的 timeout 信号触发时调用,因此该函数会一直循环发送数据直到定时器停止。如果需要在某个条件下停止发送数据,可以在 sendData 函数中添加判断逻辑。