QT的Tcp长连接代码
时间: 2024-05-06 14:03:22 浏览: 155
以下是QT的Tcp长连接示例代码:
```c++
#include <QTcpSocket>
#include <QTimer>
class TcpClient : public QObject
{
Q_OBJECT
public:
explicit TcpClient(QObject *parent = nullptr);
signals:
void receivedData(const QString &data);
public slots:
void connectToServer(const QString &host, quint16 port);
void sendData(const QString &data);
void disconnectFromServer();
private slots:
void readData();
void handleError(QAbstractSocket::SocketError error);
void reconnect();
private:
QTcpSocket *m_socket;
QTimer *m_reconnectTimer;
QString m_host;
quint16 m_port;
};
TcpClient::TcpClient(QObject *parent)
: QObject(parent)
, m_socket(new QTcpSocket(this))
, m_reconnectTimer(new QTimer(this))
{
connect(m_socket, &QTcpSocket::readyRead, this, &TcpClient::readData);
connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(handleError(QAbstractSocket::SocketError)));
connect(m_reconnectTimer, &QTimer::timeout, this, &TcpClient::reconnect);
m_reconnectTimer->setInterval(5000); // 5 seconds
}
void TcpClient::connectToServer(const QString &host, quint16 port)
{
m_host = host;
m_port = port;
m_socket->connectToHost(m_host, m_port);
}
void TcpClient::sendData(const QString &data)
{
if (m_socket->state() == QTcpSocket::ConnectedState) {
m_socket->write(data.toUtf8());
}
}
void TcpClient::disconnectFromServer()
{
m_socket->disconnectFromHost();
}
void TcpClient::readData()
{
QString data = QString::fromUtf8(m_socket->readAll());
emit receivedData(data);
}
void TcpClient::handleError(QAbstractSocket::SocketError error)
{
switch (error) {
case QAbstractSocket::RemoteHostClosedError:
// do nothing
break;
case QAbstractSocket::HostNotFoundError:
qDebug() << "Error: Host not found";
break;
case QAbstractSocket::ConnectionRefusedError:
qDebug() << "Error: Connection refused";
m_reconnectTimer->start();
break;
default:
qDebug() << "Error:" << m_socket->errorString();
m_reconnectTimer->start();
break;
}
}
void TcpClient::reconnect()
{
qDebug() << "Trying to reconnect...";
m_socket->connectToHost(m_host, m_port);
}
```
这个类实现了一个TCP客户端,它可以连接到一个TCP服务器并发送和接收数据。如果连接中断,它将自动重新连接。要使用它,只需实例化TcpClient,然后连接到它的信号和槽,如下所示:
```c++
TcpClient *client = new TcpClient(this);
connect(client, &TcpClient::receivedData, this, &MyClass::handleReceivedData);
client->connectToServer("localhost", 1234);
client->sendData("Hello, server!");
client->disconnectFromServer();
```
阅读全文