Qt 網絡通信:`QTcpServer` 監聽,新連接生成 `QTcpSocket` 處理 XML 數據解析。
兩種封裝:
A. 繼承 `QTcpSocket` → `MySocket` 內含解析邏輯。
B. 組合:自定義類 `ConnectionHandler` 持有 `QTcpSocket*` 成員,負責解析。
class ConnectionHandler : public QObject {
Q_OBJECT
QTcpSocket* socket;
XmlParser parser; // 解析邏輯分離
public:
explicit ConnectionHandler(QTcpSocket* s, QObject* parent = nullptr)
: QObject(parent), socket(s) {
connect(socket, &QTcpSocket::readyRead, this, &ConnectionHandler::onReadyRead);
connect(socket, &QTcpSocket::disconnected, this, &ConnectionHandler::deleteLater);
}
private slots:
void onReadyRead() {
QByteArray data = socket->readAll();
parser.feed(data);
while (parser.hasCompleteMessage()) {
XmlMessage msg = parser.popMessage();
handleMessage(msg); // 業務分發
}
}
};