我想做一個類,我可以序列化和反序列化一個對象。該類應該以這種方式工作:我序列化對象並將其發送到服務器,然後服務器修改我的對象的一個字段並將其發回,以便我可以反序列化接收到的對象。但是,如果我關閉了outputStream,我得到套接字寫入錯誤。如何正確關閉outputStream和inputStream?正確的方法來關閉ObjectInputStream和ObjectOutputStream
編輯: 即使我使用try-有資源,我仍然得到同樣的錯誤
public class UtilSerialize {
InetAddress address;
Socket socketConnection;
public UtilSerialize() {
try {
this.address = InetAddress.getLocalHost();
socketConnection = new Socket(address, 8000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void serializeObject() {
try {
OrdinaryUser user = new OrdinaryUser("Joe", "Joe");
ObjectOutputStream clientOutputStream = new ObjectOutputStream(socketConnection.getOutputStream());
clientOutputStream.writeObject(user);
System.out.println(user.getUsername());
//clientOutputStream.close();
} catch (Exception e) {
System.out.println(e);
}
}
public void deSerializeObject() {
try {
ObjectInputStream clientInputStream = new ObjectInputStream(socketConnection.getInputStream());
OrdinaryUser user = (OrdinaryUser) clientInputStream.readObject();
System.out.println(user.getUsername());
clientInputStream.close();
} 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(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(Unknown Source)
at java.io.ObjectOutputStream.writeNonProxyDesc(Unknown Source)
at java.io.ObjectOutputStream.writeClassDesc(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeFatalException(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at ro.unitbv.serverinvoicemanagement.classes.ServerThread.run(ServerThread.java:29)
at java.lang.Thread.run(Unknown Source)
正確的方法是[試用資源](http://stackoverflow.com/q/26516020/6948900) –
你確定你需要close()而不是flush()嗎?避免關閉底層流? –
他需要刷新然後關閉流。這只是一個安全的做法 – efekctive