我使用 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文件
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 字节数据,则读取函数返回 281 字节,但缓冲区中没有数据。
Debug:
281
data:
我不知道我做错了什么。我怎样才能使这项工作?