qt_demoe/nettool/api/tcpclient.cpp

82 lines
1.9 KiB
C++
Raw Normal View History

#include "tcpclient.h"
2021-06-08 11:02:49 +00:00
#include "quihelper.h"
TcpClient::TcpClient(QTcpSocket *socket, QObject *parent) : QObject(parent)
{
this->socket = socket;
ip = socket->peerAddress().toString();
ip = ip.replace("::ffff:", "");
port = socket->peerPort();
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(disconnected()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
}
QString TcpClient::getIP() const
{
return this->ip;
}
int TcpClient::getPort() const
{
return this->port;
}
void TcpClient::disconnected()
{
socket->deleteLater();
this->deleteLater();
emit clientDisconnected();
}
void TcpClient::readData()
{
QByteArray data = socket->readAll();
if (data.length() <= 0) {
return;
}
QString buffer;
2021-04-13 01:36:22 +00:00
if (AppConfig::HexReceiveTcpServer) {
buffer = QUIHelper::byteArrayToHexStr(data);
2021-04-13 01:36:22 +00:00
} else if (AppConfig::AsciiTcpServer) {
buffer = QUIHelper::byteArrayToAsciiStr(data);
} else {
buffer = QString(data);
}
emit receiveData(ip, port, buffer);
//自动回复数据,可以回复的数据是以;隔开,每行可以带多个;所以这里不需要继续判断
2021-04-13 01:36:22 +00:00
if (AppConfig::DebugTcpServer) {
int count = AppConfig::Keys.count();
for (int i = 0; i < count; i++) {
2021-04-13 01:36:22 +00:00
if (AppConfig::Keys.at(i) == buffer) {
sendData(AppConfig::Values.at(i));
break;
}
}
}
}
void TcpClient::sendData(const QString &data)
{
QByteArray buffer;
2021-04-13 01:36:22 +00:00
if (AppConfig::HexSendTcpServer) {
buffer = QUIHelper::hexStrToByteArray(data);
2021-04-13 01:36:22 +00:00
} else if (AppConfig::AsciiTcpServer) {
buffer = QUIHelper::asciiStrToByteArray(data);
} else {
buffer = data.toUtf8();
}
socket->write(buffer);
emit sendData(ip, port, data);
}
void TcpClient::abort()
{
socket->abort();
}