简体   繁体   English

Qt QTcpSocket异步写入

[英]Qt QTcpSocket async write

I'm trying to write a dynamic data to a QTcpSocket, this is how I implement it: 我正在尝试将动态数据写入QTcpSocket,这是我实现它的方式:

    connect(&m_tcpSocket, SIGNAL(bytesWritten(qint64)), SLOT(written(qint64)));
//...
void MyClass::written(qint64 iBytes)
{
    if(iBytes>0)
        m_strWrite = m_strWrite.mid(iBytes);
    if(m_strWrite.length()<1)
    {
        if(m_hHandle->isDone())
            m_tcpSocket.disconnectFromHost();
    }else if(m_tcpSocket.isValid()){
        m_tcpSocket.write(m_strWrite);
    }
}
//...
void MyClass::dataReady(const QByteArray &strData)
{
    bool bWrite = m_strWrite.isEmpty();
    m_strWrite.append(strData);
    if(bWrite)
        written(0);
}

dataReady is a slot which is called whenever there is some data ready, and strData is at most 8192 bytes. dataReady是一个插槽,只要准备好一些数据,就会调用该插槽,strData最多为8192字节。

This method works perfectly, but when data is huge (>500 MB), strange things happen, sometimes data is written much more than what I expect, sometimes some data is missing, sometimes nothing is written after a while and ... 此方法效果很好,但是当数据量很大(> 500 MB)时,会发生奇怪的事情,有时写入的数据超出了我的预期,有时丢失了一些数据,有时过一会儿什么也没写,并且...

I just want dynamic buffer, be written to socket, is there another way for that? 我只想将动态缓冲区写入套接字,是否还有另一种方法?

QTcpSocket has its own write buffer. QTcpSocket有自己的写缓冲区。 Just use m_tcpSocket.write(strData) . 只需使用m_tcpSocket.write(strData) Qt does not limit the write buffer size. Qt不限制写缓冲区的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM