这是我现在所拥有的。
接收者:
public static void read(Socket socket, ObjectInputStream in) {
try {
String separator = in.readUTF();
while (in.readByte() == -3) {
String path = in.readUTF().replaceAll(separator, System.getProperty("file.separator"));
File file = new File(new File(path).getParent());
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path);
int b = 0;
while ((b = in.readByte()) != -4) {
fos.write(b);
}
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
发件人:
public static void send(String[] path) {
Socket socket;
try {
socket = new Socket(ip, port);
socket.setKeepAlive(true);
} catch (UnknownHostException e) {
return;
} catch (IOException e) {
return;
}
try {
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeUTF(Devbox.getSeparator());
for (String s : path) {
send(s, out);
out.writeByte(-2);
}
out.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void send(String path, ObjectOutputStream out) {
File file = new File(path);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f : files) {
send(path + f.getName(), out);
}
} else {
try {
out.writeByte(-3);
out.writeUTF(path);
FileInputStream fis = new FileInputStream(file);
int b = 0;
while ((b = fis.read()) != -1) {
out.writeByte(b);
}
fis.close();
out.writeByte(-4);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是我在发件人中遇到的错误。
java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at java.io.ObjectOutputStream$BlockDataOutputStream.writeBlockHeader(ObjectOutputStream.java:1874)
at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1855)
at java.io.ObjectOutputStream$BlockDataOutputStream.writeByte(ObjectOutputStream.java:1895)
at java.io.ObjectOutputStream.writeByte(ObjectOutputStream.java:760)
它指向
out.writeByte(b);
它成功发送了大约 25 个文件,然后抛出此错误。每次它扔到的文件都不一样,但在5个文件左右的相同范围内。接收者在一个特定文件之后停止,该文件通常在发送者停止的文件之前一对。它停止是因为 in.readByte() == -3 是假的。当它发生时,我得到了 -85 和 16 之类的数字。我在另一台计算机上尝试了它,因为它说的是软件,它是完全相同的。有谁知道为什么会这样?我花了一天的时间试图弄清楚,但一无所获。任何帮助是极大的赞赏。