我在反序列化对象时遇到此异常:
控制台上的输出
sending request: GET_OBJS
java.io.EOFException
receiving response
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readUTFBody(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readUTF(Unknown Source)
at java.io.ObjectInputStream.readUTF(Unknown Source)
at java.io.ObjectStreamClass.readNonProxy(Unknown Source)
at java.io.ObjectInputStream.readClassDescriptor(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at thesis.bot.wab.applet.DApplet.extracted(DApplet.java:218)
我正在尝试在不使用文件的情况下反序列化对象。该对象使用DatagramSocket发送。
从一个java applet我打电话:
sendPacket("GET_OBJS");
[...]
input=new ObjectInputStream(new ByteArrayInputStream(receivedPacket.getData()));
objs=extracted(input);
toWrite=Integer.toString(objs.size());
input.close();
sendPacket("PRINT_"+toWrite);
[...]
private LinkedList<Objects> extracted(ObjectInputStream obj)
throws IOException, ClassNotFoundException {
return (LinkedList<Objects>) obj.readObject();
}
private void sendPacket(String msg) throws IOException{
System.out.println("sending request: "+msg);
buf=msg.getBytes();
DatagramPacket tosend=new DatagramPacket(buf,buf.length,addr,9999);
socket.send(tosend);
}
另一方面:
else if(req.compareTo("GET_OBJS")==0){
Environement env=(Environement) ctx.getService(ctx.getServiceReference(Environement.class.getName()));
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream out=new ObjectOutputStream(baos);
out.writeObject(env.getObjects());
out.close();
buf=baos.toByteArray();
resp="buffer_ready";
}
其中env.getObjects()返回一个LinkedList,“对象和对象是一个可序列化的类。
有什么问题?
答案 0 :(得分:2)
我已经修改了代码以使用tcp套接字而现在我没有得到异常。
修改后的代码:
从一个java applet我打电话:
sendPacket("GET_OBJS");
[...]
ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
objs=extracted(ois);
System.out.println(objs.size());
[...]
private LinkedList<Objects> extracted(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
return (LinkedList<Objects>) ois.readObject();
}
private void sendPacket(String msg) throws IOException{
bw.write(msg);
bw.newLine();
bw.flush();
System.out.println("Message sent");
}
另一方面:
else if(req.compareTo("GET_OBJS")==0){
Environement env=(Environement) ctx.getService(ctx.getServiceReference(Environement.class.getName()));
ObjectOutputStream out=new ObjectOutputStream(clientSock.getOutputStream());
out.flush();
out.writeObject(env.getObjects());
out.flush();
resp="buffer_ready";
}
现在它有效! 谢谢你的帮助!
PS:必须在开始写入之前ObjectOutputStream调用flush()。