简体   繁体   中英

SocketChannel - write does not write all the DATA

I'm trying to send data (400016 bytes) via SocketChannel. for some reason not all the data is being sent. (I expect to see that all the 400016 bytes will be sent)

Here's the code: 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;

}

I'm calling the function with byte[] of 400016.

I'm getting the following prints: Need to send message of size: 400016 Before write oper: pos:0 limit: 400016 remainging: 400016 has remaining: true After write oper: pos:262142 limit: 400016 remainging: 137874 has remaining: true sent 262142 bytes Before write oper: pos:262142 limit: 400016 remainging: 137874 has remaining: true After write oper: pos:262142 limit: 400016 remainging: 137874 has remaining: true sent 262142 bytes Finish sending data

This is the problem:

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

You don't seem able to decide the meaning of nNumOfSentBytes - on the first line it looks like you're actually treating it as the total number of bytes sent (because you're increasing it by the number of bytes you've just sent), but then on the second line you're treating it as the number of bytes you've just sent, to increase another total.

It's not clear why you've got both variables at all, to be honest. I suspect you only need one:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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