【发布时间】:2013-12-18 04:45:19
【问题描述】:
我正在尝试将文件从客户端发送到服务器。下面是我尝试过的代码。但有时,在传输过程中会出现数据包丢失。我不确定我错在哪里。
服务器端代码:
public static void ReadAndWrite(byte[] aByte, Socket clientSocket,
InputStream inputStream, String fileOutput)
throws FileNotFoundException, IOException {
int bytesRead;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try
{
fileOutputStream = new FileOutputStream( fileOutput );
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bytesRead = inputStream.read(aByte, 0, aByte.length);
System.out.println("The length is "+bytesRead);
int count = 0;
do {
count++;
byteArrayOutputStream.write(aByte);
bytesRead = inputStream.read(aByte);
} while (bytesRead != -1);
System.out.println("The count is "+count);
System.out.println("The length is "+byteArrayOutputStream.size());
bufferedOutputStream.write(byteArrayOutputStream.toByteArray());
bufferedOutputStream.flush();
bufferedOutputStream.close();
clientSocket.close();
}
catch(Exception ex)
{
Logger.writeLog(ex,Listen.class.getName(), LogType.EXCEPTION);
throw ex;
}
客户端代码:
public void readByteArrayAndWriteToClientSocket(
Socket connectionSocket, BufferedOutputStream outToClient, String fileToSend ) throws Exception
{
try{
if (outToClient != null)
{
File myFile = new File(fileToSend);
System.out.println(myFile.length());
byte[] byteArray = new byte[(int) myFile.length()];
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(myFile);
} catch (IOException ex) {
Logger.writeLog(ex, FileUtility.class.getName(), LogType.EXCEPTION);
throw ex;
}
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
try {
bufferedInputStream.read(byteArray, 0, byteArray.length);
outToClient.write(byteArray, 0, byteArray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
return;
} catch (IOException ex) {
Logger.writeLog(ex, FileUtility.class.getName(), LogType.EXCEPTION);
throw ex;
}
}
}catch (Exception e) {
Logger.writeLog(e, getClass().getName(), LogType.EXCEPTION);
throw e;
}
}
【问题讨论】:
-
代码看起来没问题。如果你区分文件,它们在哪里不同?
-
“丢包”是什么意思?部分数据没有收到?没有收到任何数据?或者用 Wireshark 之类的东西检查数据包显示数据包被丢弃?在任何有损耗的线路上,偶尔的数据包丢失是不可避免的; TCP 的设计考虑到了这一点,并构建了恢复机制以确保交付(如果可能)并保证顺序和完整性。
-
您不应在发送文件后立即关闭
socket。让它在终止前等待几秒钟。这将确保服务器实际接收到文件。 -
@ExtremeCoders:这绝对不是 Java 套接字的工作方式。如果是,你怎么知道要等多久才能关闭?
-
我正在尝试传输 3500 KB 的 ZIP 文件。但传输的文件只有 3450 KB 或 3495 KB。我很少得到完整的文件。