Java SocketChannel-write不会写入所有数据
我正在尝试通过SocketChannel发送数据(400016字节)。 由于某些原因,并非所有数据都在发送。(我希望看到所有400016字节都将被发送) 代码如下: 公共布尔发送(字节[]字节有效载荷,int nSize){Java SocketChannel-write不会写入所有数据,java,bytebuffer,socketchannel,Java,Bytebuffer,Socketchannel,我正在尝试通过SocketChannel发送数据(400016字节)。 由于某些原因,并非所有数据都在发送。(我希望看到所有400016字节都将被发送) 代码如下: 公共布尔发送(字节[]字节有效载荷,int nSize){ System.out.print(“\n用于发送大小为“+nSize”的消息); m_sendBuf.clear(); m_sendBuf.put(字节有效载荷); m_sendBuf.flip(); 试试{ int nNumOfSentBytes=0; int ntota
System.out.print(“\n用于发送大小为“+nSize”的消息);
m_sendBuf.clear();
m_sendBuf.put(字节有效载荷);
m_sendBuf.flip();
试试{
int nNumOfSentBytes=0;
int ntotalnumosentbytes=0;
而(nTotalNumOfSentBytes
}
我正在调用字节为400016的函数
我得到了以下指纹:
需要发送邮件大小:400016
写入操作前:位置:0限制:400016剩余:400016剩余:真
写入操作后:pos:262142限制:400016剩余:137874剩余:真
发送262142字节
写入操作前:pos:262142限制:400016剩余:137874剩余:真
写入操作后:pos:262142限制:400016剩余:137874剩余:真
发送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
}
int bytesSent=0;
while(bytesSent
你好,谢谢。你将如何在接收器处编写代码?我将得到400016字节?还是更多字节?(如果更多,我如何从中构建消息?)
int bytesSent = 0;
while (bytesSent < size) {
bytesSent += m_socketChannel.write(m_sendBuf);
// Add whatever diagnostics you need
}