|
| 1 | +#include "tcpconnection.h" |
| 2 | + |
| 3 | +#include "aopacket.h" |
| 4 | + |
| 5 | +TcpConnection::TcpConnection(AOApplication *ao_app, QObject *parent) |
| 6 | + : AOConnection(ao_app, parent) |
| 7 | + , m_socket(new QTcpSocket(this)) |
| 8 | +{ |
| 9 | + connect(m_socket, &QTcpSocket::connected, this, &TcpConnection::onConnected); |
| 10 | + connect(m_socket, &QTcpSocket::disconnected, this, &TcpConnection::onDisconnected); |
| 11 | + connect(m_socket, &QAbstractSocket::errorOccurred, this, &TcpConnection::onError); |
| 12 | + connect(m_socket, &QTcpSocket::readyRead, this, &TcpConnection::onReadyRead); |
| 13 | +} |
| 14 | + |
| 15 | +TcpConnection::~TcpConnection() |
| 16 | +{ |
| 17 | + m_socket->disconnect(this); |
| 18 | + disconnectFromServer(); |
| 19 | +} |
| 20 | + |
| 21 | +bool TcpConnection::isConnected() |
| 22 | +{ |
| 23 | + return m_socket->state() == QAbstractSocket::ConnectedState; |
| 24 | +} |
| 25 | + |
| 26 | +void TcpConnection::connectToServer(const ServerInfo &server) |
| 27 | +{ |
| 28 | + disconnectFromServer(); |
| 29 | + m_buffer.clear(); |
| 30 | + m_socket->connectToHost(server.address, server.port); |
| 31 | +} |
| 32 | + |
| 33 | +void TcpConnection::disconnectFromServer() |
| 34 | +{ |
| 35 | + if (isConnected()) |
| 36 | + { |
| 37 | + m_socket->disconnectFromHost(); |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +void TcpConnection::sendPacket(AOPacket packet) |
| 42 | +{ |
| 43 | + m_socket->write(packet.toString(true).toUtf8()); |
| 44 | +} |
| 45 | + |
| 46 | +void TcpConnection::onConnected() |
| 47 | +{ |
| 48 | + Q_EMIT connectedToServer(); |
| 49 | +} |
| 50 | + |
| 51 | +void TcpConnection::onDisconnected() |
| 52 | +{ |
| 53 | + Q_EMIT disconnectedFromServer(); |
| 54 | +} |
| 55 | + |
| 56 | +void TcpConnection::onError(QAbstractSocket::SocketError error) |
| 57 | +{ |
| 58 | + Q_UNUSED(error); |
| 59 | + Q_EMIT errorOccurred(m_socket->errorString()); |
| 60 | +} |
| 61 | + |
| 62 | +void TcpConnection::onReadyRead() |
| 63 | +{ |
| 64 | + m_buffer += QString::fromUtf8(m_socket->readAll()); |
| 65 | + |
| 66 | + while (true) |
| 67 | + { |
| 68 | + int end = m_buffer.indexOf("#%"); |
| 69 | + if (end == -1) |
| 70 | + { |
| 71 | + break; |
| 72 | + } |
| 73 | + |
| 74 | + QString message = m_buffer.left(end); |
| 75 | + m_buffer = m_buffer.mid(end + 2); |
| 76 | + |
| 77 | + QStringList raw_content = message.split('#'); |
| 78 | + if (raw_content.isEmpty()) |
| 79 | + { |
| 80 | + continue; |
| 81 | + } |
| 82 | + const QString header = raw_content.takeFirst(); |
| 83 | + for (QString &data : raw_content) |
| 84 | + { |
| 85 | + data = AOPacket::decode(data); |
| 86 | + } |
| 87 | + |
| 88 | + Q_EMIT receivedPacket(AOPacket(header, raw_content)); |
| 89 | + } |
| 90 | +} |
0 commit comments