用QT写一个网络通信类,用于接收和发送QByteArray数据
时间: 2024-09-20 15:13:04 浏览: 39
在Qt中,你可以使用QTcpSocket或QUdpSocket来处理TCP或UDP网络通信。以下是一个简单的例子,展示了如何创建一个基础的网络通信类,用于接收和发送`QByteArray`数据:
```cpp
#include <QObject>
#include <QHostAddress>
#include <QTcpSocket>
#include <QByteArray>
class NetworkCommunicator : public QObject
{
Q_OBJECT
public:
explicit NetworkCommunicator(QHostAddress address, quint16 port, QObject *parent = nullptr)
: QObject(parent), socket(address, Qt::DirectConnection, port)
{
connect(&socket, &QTcpSocket::connected, this, &NetworkCommunicator::connected);
connect(&socket, &QTcpSocket::readyRead, this, &NetworkCommunicator::readData);
connect(&socket, &QTcpSocket::disconnected, this, &NetworkCommunicator::disconnected);
}
~NetworkCommunicator()
{
if (isConnected())
disconnectFromHost();
}
void sendData(QByteArray data)
{
if (!socket.isOpen()) {
qDebug() << "Socket is not open. Opening...";
socket.open(QIODevice::WriteOnly);
if (!socket.waitForConnected(5000)) {
qWarning() << "Failed to connect";
return;
}
}
qint64 bytesWritten = socket.write(data);
if (bytesWritten == -1) {
qWarning() << "Failed to write data";
} else {
qDebug() << "Sent" << bytesWritten << "bytes";
}
}
QByteArray receiveData()
{
if (!socket.bytesAvailable()) {
qDebug() << "No data available";
return QByteArray();
}
QByteArray receivedData;
qint64 bytesRead = socket.read(receivedData);
if (bytesRead > 0) {
qDebug() << "Received" << bytesRead << "bytes";
return receivedData;
} else {
qWarning() << "Failed to read data";
}
return QByteArray();
}
signals:
void connectionEstablished();
void dataReceived(QByteArray data);
private slots:
void connected()
{
emit connectionEstablished();
}
void disconnected()
{
emit dataReceived(QByteArray());
}
private:
QTcpSocket socket;
bool isConnected() const { return socket.state() == SocketState::Open; }
// Disconnection method
void disconnectFromHost()
{
socket.disconnectFromHost();
}
};
```
这个`NetworkCommunicator`类接受一个IP地址、端口作为参数,并维护一个`QTcpSocket`实例。它提供了`sendData`和`receiveData`方法用于传输数据。当连接建立时,会发出`connectionEstablished`信号;当接收到数据时,会发出`dataReceived`信号。
要使用这个类,你需要创建一个实例并连接到所需的服务器:
```cpp
NetworkCommunicator communicator("127.0.0.1", 12345);
connect(&communicator, &NetworkCommunicator::dataReceived, yourReceiverObject, &YourReceiverClass::handleDataReceived);
```
阅读全文