HxUtils/HxSocket.cpp

94 lines
2.2 KiB
C++
Raw Normal View History

2024-01-11 16:14:21 +08:00
#include "HxSocket.h"
#include "HxThread.h"
#include <QHostInfo>
HxSocket::HxSocket(quint16 port)
{
connect(&server, &QTcpServer::newConnection, this, &HxSocket::new_connection);
server.listen(QHostAddress::Any, port);
}
HxSocket::HxSocket(QString address, int port)
{
is_reconnect = true;
socket = new QTcpSocket();
connect(socket, &QTcpSocket::readyRead, this, &HxSocket::ready_read);
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::QueuedConnection);
connect(this, &HxSocket::reconnection_event, this, &HxSocket::reconnection);
/* 域名解析 */
QHostInfo info = QHostInfo::fromName(address);
this->port = port;
this->address = info.addresses().at(0).toString();
reconnection();
}
void HxSocket::new_connection()
{
if (socket != nullptr)
socket->abort();
socket = server.nextPendingConnection();
connect(socket, &QTcpSocket::readyRead, this, &HxSocket::ready_read);
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::QueuedConnection);
}
void HxSocket::write(QByteArray data)
{
if (socket == nullptr || socket->state() != QTcpSocket::ConnectedState)
return;
data.append('\n');
socket->write(data);
socket->flush();
}
void HxSocket::ready_read()
{
QByteArray msg = socket->readAll();
emit data_receive_event(msg.data());
}
void HxSocket::disconnected()
{
if (is_reconnect)
emit reconnection_event();
}
void HxSocket::reconnection()
{
/* 取消已有的连接 */
if (socket != nullptr)
socket->disconnectFromHost();
/* 连接服务器 */
socket->connectToHost(address, port);
/* 等待连接 */
if (!socket->waitForConnected(500))
{
/* 使用 QThread::msleep 延时,会使 Socket 出现接收不到事件信息 (槽无法响应) */
// auto time = QTime::currentTime().addMSecs(10000);
// while (QTime::currentTime() < time)
// {
// QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
// QThread::msleep(100);
// }
HxThread::sleep(10000);
emit reconnection_event();
}
}