我使用QTcpSocket打开连接并接收数据。但我从插槽读取数据时遇到问题。
//头文件
class PeerWireClient : public QTcpSocket
{
Q_OBJECT
public:
PeerWireClient(QObject *parent = 0);
private slots:
void readFromSocket();
private:
qint64 socketBytesAvailable() const { return QTcpSocket::bytesAvailable(); }
// Data waiting to be read/written
QByteArray incomingBuf;
QByteArray outgoingBuf;
};
// cpp file
PeerWireClient::PeerWireClient(QObject *parent) :
QTcpSocket(parent)
{
connect(this, SIGNAL(readyRead()), this, SLOT(readFromSocket()));
}
void PeerWireClient::readFromSocket(void)
{
qint64 oldsize, size;
qint64 readbytes = 0;
oldsize = incomingBuf.size();
size = socketBytesAvailable();
if (size > 0) {
incomingBuf.resize(oldsize + size);
readbytes = read((incomingBuf.data()+oldsize), size);
qDebug("%ld", readbytes); //
qDebug("data: %s", incomingBuf.constData());
}
}
如果我尝试从另一侧发送281个字节的数据 read函数返回281个字节,但缓冲区中没有数据。
Debug:
281
data:
我不知道我做错了什么。我怎样才能做到这一点?