2024-11-25 17:15:44 +08:00

85 lines
1.6 KiB
C++

#include "tcpclientequipment.h"
TcpClientEquipment::TcpClientEquipment(QObject *parent) : QObject(parent)
{
this->flag=false;
}
void TcpClientEquipment::setInfo(QString strIP, int iPort)
{
this->ip=strIP;
this->port=iPort;
}
void TcpClientEquipment::connect2Server()
{
this->mClient=new QTcpSocket(this);
connect(mClient,&QTcpSocket::readyRead,this,&TcpClientEquipment::onDataReceived);
this->mClient->connectToHost(QHostAddress(ip),port,QTcpSocket::ReadWrite);
this->flag=true;
}
void TcpClientEquipment::connect2Server(QString strIP, int iPort)
{
setInfo(strIP,iPort);
this->mClient=new QTcpSocket(this);
connect(mClient,&QTcpSocket::readyRead,this,&TcpClientEquipment::onDataReceived);
this->mClient->connectToHost(QHostAddress(ip),port,QTcpSocket::ReadWrite);
this->flag=true;
}
bool TcpClientEquipment::getState()
{
return this->flag;
}
bool TcpClientEquipment::sendMsg(QByteArray buffer)
{
if(this->flag){
int iResult = this->mClient->write(buffer);
if(iResult==-1){
return false;
}
else
{
return true;
}
}
else
{
return false;
}
}
bool TcpClientEquipment::sendMsg(QString buffer)
{
return this->sendMsg(buffer.toUtf8());
}
void TcpClientEquipment::reconnect2Server()
{
disconnect2Server();
connect2Server();
}
void TcpClientEquipment::disconnect2Server()
{
if(this->flag){
mClient->close();
mClient->deleteLater();
mClient=nullptr;
}
}
void TcpClientEquipment::onDataReceived()
{
QByteArray revBuffer=this->mClient->readAll();
dateReceived(revBuffer);
}