我正在尝试通过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;
}
我正在用byte [] 400016调用函数。
我收到以下照片: 需要发送尺寸为400016的留言信息 在写oper之前:pos:0 limit:400016 remaing:400016剩余:true 写oper后:pos:262142限制:400016重拍:137874剩余:为真 发送了262142个字节 在写oper之前:pos:262142 limit:400016 remaing:137874剩余:true 写oper后:pos:262142限制:400016重拍:137874剩余:为真 发送了262142个字节 完成发送数据
答案 0 :(得分:1)
这是问题所在:
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
}