java中在socket上重新建立ObjectInputStream和ObjectOutputStream的问题

来源:互联网 发布:淘宝售前客服设置 编辑:程序博客网 时间:2024/05/16 08:06

对一个socket,取其ObjectInputStream input和ObjectOutputStream output。在操作完之后,用input.close()和output.close()关闭了IO流。但是,当第二次重新打开ObjectInputStream input和ObjectOutputStream output时,会发生错误。

解释:当第一次对一个socket的输入输出流操作时,会写入/读取一些额外信息;而第二次,继续对这个socket的输入输出流操作时,不应该写入/读取额外信息

解决方法:继承ObjectInputStream和ObjectOutputStream,重写其中的两个方法

public class MyObjectOutputStream extends ObjectOutputStream {public MyObjectOutputStream() throws IOException {super();}public MyObjectOutputStream(OutputStream out) throws IOException {super(out);}@Overrideprotected void writeStreamHeader() throws IOException {return;}}public class MyObjectInputStream extends ObjectInputStream {public MyObjectInputStream() throws IOException {super();}public MyObjectInputStream(InputStream in) throws IOException {super(in);}@Overrideprotected void readStreamHeader() throws IOException {return;}}


判断是否是对socket的输入输出流的第一次操作

是则创建 ObjectInputStream和ObjectOutputStream对象

否则创建MyObjectInputStream和MyObjectOutputStream对象