2021-01-24 08:04:48 +00:00
|
|
|
|
#include "tcpclient.h"
|
2021-06-08 11:02:49 +00:00
|
|
|
|
#include "quihelper.h"
|
2021-01-24 08:04:48 +00:00
|
|
|
|
|
|
|
|
|
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) {
|
2021-01-24 08:04:48 +00:00
|
|
|
|
buffer = QUIHelper::byteArrayToHexStr(data);
|
2021-04-13 01:36:22 +00:00
|
|
|
|
} else if (AppConfig::AsciiTcpServer) {
|
2021-01-24 08:04:48 +00:00
|
|
|
|
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();
|
2021-01-24 08:04:48 +00:00
|
|
|
|
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));
|
2021-01-24 08:04:48 +00:00
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void TcpClient::sendData(const QString &data)
|
|
|
|
|
{
|
|
|
|
|
QByteArray buffer;
|
2021-04-13 01:36:22 +00:00
|
|
|
|
if (AppConfig::HexSendTcpServer) {
|
2021-01-24 08:04:48 +00:00
|
|
|
|
buffer = QUIHelper::hexStrToByteArray(data);
|
2021-04-13 01:36:22 +00:00
|
|
|
|
} else if (AppConfig::AsciiTcpServer) {
|
2021-01-24 08:04:48 +00:00
|
|
|
|
buffer = QUIHelper::asciiStrToByteArray(data);
|
|
|
|
|
} else {
|
|
|
|
|
buffer = data.toUtf8();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
socket->write(buffer);
|
|
|
|
|
emit sendData(ip, port, data);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void TcpClient::abort()
|
|
|
|
|
{
|
|
|
|
|
socket->abort();
|
|
|
|
|
}
|