第一步:.pro工程文件添加
QT += network
第二步:.h文件添加代码
#ifndef TCPCLIENT_H
#define TCPCLIENT_H
#include <QException>
#include <QDebug>
#include <QTcpSocket>
#include <QHostAddress>
class TCPClient: public QObject
{
Q_OBJECT
public:
TCPClient();
bool openTcpClient(QString ip, qint16 port);
void closeTcpClient();
bool sendData(QString msg);
bool getConnectStatus();
private:
void readData();
private:
QTcpSocket *socket = nullptr;
qint32 MAX_BUFFER = 1024 * 10;
signals:
//信号没有返回值,可以有参数,信号函数不需要定义,只需要声明
void pushClient_singal(QByteArray buffer, qint64 length);
};
#endif // TCPCLIENT_H
第三步:.cpp文件添加代码
#include "tcpclient.h"
TCPClient::TCPClient()
{
}
// 打开网络连接
bool TCPClient::openTcpClient(QString ip, qint16 port)
{
try {
closeTcpClient();
// 创建通信的套接字
socket = new QTcpSocket(this);
socket->abort(); //取消原有连接
// 接受到服务端消息
connect(socket, &QTcpSocket::readyRead, this, [ = ]() {
readData();
});
// 服务器端断开连接
connect(socket, &QTcpSocket::disconnected, this, [ = ]() {
closeTcpClient();
});
// 检测连接状态
connect(socket, &QTcpSocket::connected, this, [ = ]() {
});
socket->connectToHost(QHostAddress(ip), port);
// 等待连接成功
if(socket->waitForConnected()) {
return true;
}
} catch (std::exception ex) {
qCritical() << "打开网络连接失败:" << ex.what();
}
return false;
}
// 关闭网络
void TCPClient::closeTcpClient()
{
try {
if(socket != NULL&&socket->state()) {
socket->disconnectFromHost();
socket->abort();
socket->close();
socket->deleteLater();
socket = nullptr;
}
} catch (std::exception ex) {
qCritical() << "关闭网络连接失败:" << ex.what();
}
}
// 发送数据
bool TCPClient::sendData(QString msg)
{
try {
if(socket != nullptr && socket->isOpen()) {
// (msg.toUtf8();//转换成utf8格式的字节流发送
// 按十六进制编码发送
QByteArray byte = QByteArray::fromHex (msg.toLatin1().data());//按十六进制编码发送
socket->write(byte);
//判断是否写入成功
bool iswrite = socket->waitForBytesWritten();
if (iswrite) {
//写入成功
return true;
} else {
//没有写入成功
return false;
}
}
} catch (std::exception ex) {
qCritical() << "客户端发送失败:" << ex.what();
}
return false;
}
// 获取连接状态
bool TCPClient::getConnectStatus()
{
return socket->state();
}
// 接收数据
void TCPClient::readData()
{
try {
// 设置每次读取最大缓存数据
QByteArray receiveByte = socket->read(MAX_BUFFER);
// 一次读取全部缓存数据
//QByteArray receiveByte = m_socket->readAll();
if(receiveByte.count() > 0) {
pushClient_singal(receiveByte, receiveByte.count());
} else {
qInfo() << "读取不到数据";
}
} catch (std::exception ex) {
qCritical() << "读取数据失败:" << ex.what();
}
}
标签:TCPClient,QByteArray,QT,TCP,receiveByte,QTcpSocket,网络连接,include,socket
From: https://www.cnblogs.com/qiutian-hao/p/18222462