我正在使用tcp套接字的文件传输应用程序。在正常情况下,当我尝试使用应用程序发送文件时,会收到完整的文件,但是当我在收到的每个数据包之间放置40毫秒的睡眠时,我只收到部分文件。我也在将完整文件发送到输出流后立即关闭套接字。可能是我没有收到完整文件的可能原因?以下是发送方和接收方的代码。提前谢谢。
/////////////////////////Sender Side////////////////////////////
bytesLeft = fileSize;
while(bytesLeft > 0)
{
try
{
bytesRead = fileInpStream.read(buffer, 0, BUFFERSIZE);
outStream.write(Arrays.copyOfRange(buffer, 0, bytesRead));
}
catch (IOException e)
{
try
{
fileInpStream.close();
}
catch (IOException e1)
{
Log.i(LOGC, "Error " + e1.getMessage());
e1.printStackTrace();
disconnect();
return;
}
}
bytesLeft -= bytesRead;
if (bytesLeft < 1)
{
try
{
fileInpStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
//Closing the socket immediately after all the data are sent to out stream.
try
{
socket.close();
}
catch (StcException e)
{
e.printStackTrace();
}
/////////////////Receiver Side//////////////////////////
bytesLeft = filesize;
while (bytesLeft > 0)
{
try
{
if (bytesLeft < BUFFERSIZE)
readAmount = (int) bytesLeft;
bytesRead = inpstream.read(buf, 0, readAmount);
if (bytesRead < 1)
{
fileoutputstream.close();
}
fileoutputstream.write(Arrays.copyOfRange(buf, 0,bytesRead));
bytesLeft -= bytesRead;
//Including a sleep of 40 ms or more doesnt completely receive the data.
//try{ sleep(40) } catch(Exception e){ }
if (bytesLeft == 0)
{
fileoutputstream.close();
}
}
catch (IOException e)
{
try
{
fileoutputstream.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
答案 0 :(得分:0)
你首先不需要睡觉。把它拿出来。这只是浪费时间。你的代码是它需要的复杂几倍,并且可能掩盖了一些潜伏的错误。这样:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
out.close();
两端都足够了。