0

I get sine wave from server though TCP and plot it. Everything seems to be fine until I start sending something back at c>1000. After one byte sent, I still get data but the waveform of sine wave is changed. I'm sure that there are some missed data but I can't find bugs in my code. The transmission rate is about 1M bps.

The question is

  1. When I write something to server, how it effects to socket?

  2. Why the socket miss some data?

  3. How can I fix it?

    ssTcpClient::ssTcpClient(QObject *parent) :
    QObject(parent)
    {
        socket = new QTcpSocket(this);
        connect(socket, SIGNAL(connected()),
                this, SLOT(on_connected()));
        connect(socket, SIGNAL(disconnected()),
                this, SLOT(on_disconnected()));
    }
    
    void ssTcpClient::on_connected()
    {
        qDebug() << "Client: Connection established.";
        connect(socket, SIGNAL(readyRead()),
                this, SLOT(on_readyRead()));
        in = new QDataStream(socket);
    }
    
    void ssTcpClient::on_readyRead(){
        static quint32 c = 0;
        qDebug() << "c" << c++;
    
        QVector<quint8> data;
        quint8 buf;
        while(socket->bytesAvailable()>0){
            //read data to buffer
            *in >> buf;
            data.append(buf);
        }
        //process data
        emit data_read(data);
    
        //if there are over 1000 data then send something back
        if(c>1000){
            char msg[10];
            msg[0] = 'c';
            socket->write(msg,1);
            socket->flush();
        }
    
    }
    
4

1 回答 1

3

您不能依赖 TCP 流量来完成,数据以无法确定的块的形式到达。

您正在使用QDataStream从套接字读取数据。这是一个非常糟糕的主意,因为QDataStream假设您拥有完整的数据集。如果没有足够的数据,它将默默地失败。

我建议您修改您的数据源,以便它首先发送一个字节数,或者它发送某种终止序列,您可以注意它告诉您已收到足够的处理。

于 2014-03-04T13:49:54.190 回答