【QT】TCP服务端网络通信
第一步:.pro工程文件添加
QT += network
第二步:.h文件添加
#ifndef TCPSERVER_H
#define TCPSERVER_H
#include <QException>
#include <QDebug>
#include <QTcpServer>
#include <QTcpSocket>
class TcpServer: public QObject
{
Q_OBJECT
public:
TcpServer();
bool openNetWork(qint16 port);
void closeNetWork();
bool getNetWorkStatus();
void sendData(QString msg);
private:
void connection();
void disConnected(QTcpSocket tcp);
private:
QTcpServer *m_s = nullptr;
QTcpSocket *m_tcp = nullptr;
signals:
//信号没有返回值,可以有参数,信号函数不需要定义,只需要声明
void pushNetwork_singal(QByteArray buffer, qint64 length);
};
#endif // TCPSERVER_H
第三步:.cpp文件添加
#include "tcpserver.h"
TcpServer::TcpServer()
{
}
// 开启网络监听
bool TcpServer::openNetWork(qint16 port)
{
try {
closeNetWork();
// 创建监听的套接字
m_s = new QTcpServer(this);
// 信号/槽绑定监听客户端接入
connect(m_s, &QTcpServer::newConnection, this, &TcpServer::connection, Qt::QueuedConnection);
// 开启监听
m_s->listen(QHostAddress::Any, port);
return m_s->isListening();
} catch (std::exception ex) {
qDebug() << "打开网络监听失败:" << ex.what();
}
return false;
}
// 关闭网络监听
void TcpServer::closeNetWork()
{
if(m_tcp != NULL && m_tcp->isOpen()) {
m_tcp->close();
m_tcp->deleteLater();
m_tcp = nullptr;
}
if(m_s != NULL && m_s->isListening()) {
m_s->close();
m_s->deleteLater();
m_s = nullptr;
}
}
// 获取网络状态
bool TcpServer::getNetWorkStatus()
{
return m_s->isListening();
}
// 客户端接入
void TcpServer::connection()
{
try {
qDebug() << "客户端接入";
// 创建用于通信的套接字
m_tcp = m_s->nextPendingConnection();
// 检测是否可以接受数据
connect(m_tcp, &QTcpSocket::readyRead, this, [ = ]() {
try {
QByteArray data = m_tcp->readAll();
pushNetwork_singal(data, data.count());
} catch (std::exception ex) {
qDebug() << "读取数据失败:" << ex.what();
}
});
// 断开连接
connect(m_tcp, &QTcpSocket::disconnected, this, [ = ]() {
try {
qDebug() << "客户端断开";
m_tcp->close();
m_tcp->deleteLater();
m_tcp = nullptr;
} catch (std::exception ex) {
qDebug() << "客户端连接断开处理失败:" << ex.what();
}
});
} catch (std::exception ex) {
qDebug() << "客户端接入失败:" << ex.what();
}
}
// 发送数据
void TcpServer::sendData(QString msg)
{
if(m_tcp != nullptr && m_tcp->isOpen()) {
// (msg.toUtf8();//转换成utf8格式的字节流发送
// 按十六进制编码发送
QByteArray byte = QByteArray::fromHex (msg.toLatin1().data());//按十六进制编码发送
m_tcp->write(byte);
}
}