我使用RMI和套接字在客户端集之间传输文件。问题是当运行下面的代码时有时我在客户端获得此异常:
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2671)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3146)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:858)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:354)
at javafxcyberwind.serverSocket.run(serverSocket.java:38)
at java.lang.Thread.run(Thread.java:748)
这是我的代码示例,例外情况在注释行中:
客户:
Server_MethodsPEER S = (Server_MethodsPEER) Naming.lookup("rmi://" + ip + ":" + port + "/" + email);
Server_Methods R = S.peer();
R.uploadToServer(fileName);
Socket s = new Socket(ip, R.getServerSocketPort());
File fres = new File(crep + fileName);
FileInputStream inf = new FileInputStream(fres);
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
byte buf[] = new byte[1024];
int nn;
while ((nn = inf.read(buf)) != -1) {
out.write(buf, 0, nn);
}
out.close();
inf.close();
s.close();
fres.delete();
服务器:
public class serverSocket implements Runnable {
private final ServerSocket socketserver;
private Socket socket;
private final String ff;
private final String rp;
public serverSocket(ServerSocket s, String file, String rep) {
socketserver = s;
ff = file;
rp = rep;
}
@Override
public void run() {
try {
socket = socketserver.accept();
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());//EOFException here
FileOutputStream out = new FileOutputStream(new File(rp + ff));
byte buf[] = new byte[1024];
int n;
while ((n = in.read(buf)) != -1) {
out.write(buf, 0, n);
}
in.close();
out.close();
socket.close();
socketserver.close();
} catch (IOException e) {
System.err.println("socket err");
}
}
}
//ServerIMPL
ServerSocket sv;
public void uploadToServer(String fileName) throws RemoteException {
try {
sv = new ServerSocket(0);
} catch (IOException ex) {
Logger.getLogger(Cloud_ServeurIMPL.class.getName()).log(Level.SEVERE, null, ex);
}
Thread t = new Thread(new serverSocket(sv, file, crep));
t.start();
Client3_MethodsPEER M = (Client3_MethodsPEER) Naming.lookup("rmi://" + ip + ":" + port + "/" + email);
Client3_Methods U = M.peer();
U.uploadToServer(fileName);
Socket s = new Socket(ip, U.getServerSocketPort());
File fres = new File(crep + fileName);
FileInputStream inf = new FileInputStream(fres);
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
byte buf[] = new byte[1024];
int nn;
while ((nn = inf.read(buf)) != -1) {
out.write(buf, 0, nn);
}
out.close();
inf.close();
s.close();
fres.delete();
U.operation();//FileNotFoundException here (use the received files as arguments)
}
一切似乎都很好。为什么会发生这种情况以及如何解决?
答案 0 :(得分:1)
FileNotFoundException
有两个含义:
例如,如果您发送的文件名包含服务器上不存在的目录,您将从FileNotFoundException
获得new FileOutputStream
。
您的问题中没有足够的信息(即任何信息)可以对此进行更多说明。
然而:
您不需要此对象流,甚至数据输入/输出流。您只使用基本的read()
和write()
方法,因此您也可以直接使用套接字流。
你应该使用比1024字节更大的缓冲区,比如8192或其倍数。
您可以通过我对this question的回答中提供的技巧,为每个连接发送多个文件。