繁体   English   中英

SocketChannel-写不会写所有数据

[英]SocketChannel - write does not write all the DATA

我正在尝试通过SocketChannel发送数据(400016字节)。 由于某种原因,并非所有数据都已发送。 (我希望看到所有400016字节都将被发送)

这是代码:public boolean send(byte [] bytesPayload,int nSize){

    System.out.print("\nNeed to send message of size: " + nSize);
    m_sendBuf.clear();
    m_sendBuf.put(bytesPayload);
    m_sendBuf.flip();   

    try {           
            int nNumOfSentBytes = 0;
            int nTotalNumOfSentBytes = 0;               
            while(nTotalNumOfSentBytes < nSize) {
                System.out.print("\nBefore write oper: pos:" + m_sendBuf.position() + " limit: " + m_sendBuf.limit() + " remainging: " + m_sendBuf.remaining() + " has remaining: " + m_sendBuf.hasRemaining());
                nNumOfSentBytes += m_socketChannel.write(m_sendBuf);
                System.out.print("\nAfter write oper: pos:" + m_sendBuf.position() + " limit: " + m_sendBuf.limit() + " remainging: " + m_sendBuf.remaining() + " has remaining: " + m_sendBuf.hasRemaining());
                nTotalNumOfSentBytes += nNumOfSentBytes; 
                System.out.print("\nsent " + nNumOfSentBytes + " bytes"); 
            }                   
    } catch (IOException e) {           
        System.out.print("\n" + e);
        return false;
    }

    System.out.print("\nFinish sending data");
    return true;

}

我用400016的byte []调用函数。

我正在打印以下内容:需要发送以下消息:400016写入操作符之前:pos:0限制:400016剩余量:400016剩余量:true写入操作符:pos:262142限制:400016剩余量:137874剩余时间:true发送262142字节在写操作符之前:pos:262142限制:400016剩余:137874还剩余:true在写操作符之后:pos:262142限制:400016还剩下:137874剩余:true已发送262142字节完成发送数据

这就是问题:

nNumOfSentBytes += m_socketChannel.write(m_sendBuf);
nTotalNumOfSentBytes += nNumOfSentBytes; 

您似乎无法决定nNumOfSentBytes的含义-在第一行上,您似乎实际上将其视为已发送的字节总数 (因为您将其增加了刚发送的字节数) ),但是在第二行中,您将其视为刚刚发送的字节数,以增加另一个总数。

老实说,目前尚不清楚为什么同时拥有两个变量。 我怀疑您只需要一个:

int bytesSent = 0;
while (bytesSent < size) {
    bytesSent += m_socketChannel.write(m_sendBuf);
    // Add whatever diagnostics you need
}

暂无
暂无

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

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