[英]Transferring Multiple files using Java Sockets - Broken Pipe Exception
我一直在尝试编写一个使用Java套接字发送多个文件的客户端/服务器应用程序。 我已经仔细研究了与此相关的每个线程,但是我无法弄清楚为什么我发送套接字的代码在写入套接字时会抛出“管道中断”异常。 我真的可以使用一些帮助; 我已经在阳光下尝试了所有方法,但无法弄清楚。
编辑-谢谢大家! 下面的代码运行完美。
发件人代码:
long size;
dos.writeInt(fileArray.length);
//send every file in array
for (File fileArray1 : fileArray) {
int bytesRead = 0;
fis = new FileInputStream(fileArray1);
//send filename
dos.writeUTF(fileArray1.getName());
//send file size (bytes)
dos.writeLong(size = fileArray1.length());
System.out.println("Size: " + size);
//send file
try {
while ((bytesRead = fis.read(buf)) != -1) {
dos.write(buf, 0, bytesRead);
publish(new Progress(null, (int) ((sentByteCount / totalByteCount) * 100)));
}
dos.flush();
} catch (IOException ex) {
System.out.println("ERROR!!!!");
}
//close file stream, has been sent at this point
fis.close();
}
System.out.println("Done sending files");
dos.close();
clientSocket.close();
接收方代码:
while (true) {
socket = serverSocket.accept();
dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
//get number of files being received
numFiles = dis.readInt();
//read all files
for (int i = 0; i < numFiles; i++) {
filename = dis.readUTF();
System.out.println("Receiving " + filename);
size = dis.readLong();
file = new File(filename);
fos = new FileOutputStream(filename);
long total = 0;
int count = 0;
while ((total < size) && ((count = dis.read(buf, 0, (int) Math.min(buf.length, size - total))) > 0)){
fos.write(buf, 0, count);
total += count;
}
fos.close();
System.out.println("Received file " + filename);
}
dis.close();
}//end while
接收器中的这一行具有重要的返回值!
dis.read(buf);
最有可能的是,您只想使用readFully()
。
另外,您无需为接收器中的每次读取创建缓冲区,而是使用多参数读取方法。
编辑后,您的写循环仍然是错误的。 您正在使用以下语句在文件末尾写入垃圾:
fos.write(buf);
编写该循环的正确方法如下:
long total = 0;
while (total < size && (count = in.read(buffer, 0, size-total > buffer.length ? buffer.length : (int)(size-total))) > 0)
{
fos.write(buffer, 0, count);
total += count;
}
fos.close();
这样,您就不必在文件末尾写垃圾邮件,也不需要DataInputStream
。
注意:
您不需要这个:
if (!file.exists()) file.createNewFile();
调用new FileOutputStream()
已完成所有操作。 您只是在重复操作系统已经完成的工作,无论如何它仍然会做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.