关于用ObjectInputStream封装socket输入流后程序阻塞的问题
下面的代码运行后在(2)和(3)处会阻塞住
public class Server {
public static void main(String[] args)throws Exception{
  ServerSocket ssock=new ServerSocket(3000);
  Socket sock=ssock.accept();
  ObjectInputStream in=new ObjectInputStream(sock.getInputStream());    //(2)
  ObjectOutputStream out=new ObjectOutputStream(sock.getOutputStream()); //(1)
         while(true){
    out.writeObject("s");
    out.flush();
  }
}
}
public class Client {
public static void main(String[] args)throws Exception{
  Socket sock=new Socket("127.0.0.1",3000);
      ObjectOutputStream out=new ObjectOutputStream(sock.getOutputStream());//(3)
  ObjectInputStream in=new ObjectInputStream(sock.getInputStream());    //(4)
      while(true){
    out.writeObject("s");
    System.out.println((String)in.readObject());
  }
}
}
而把(1)和(2),(3)和(4)对调后程序运行正常。
原因如下:
使用缺省的serializetion的实现时,一个ObjectOutputStream的构造和一个ObjectInputStream的构造必须一一对应.ObjectOutputStream的构造函数会向输出流中写入一个标识头,而ObjectInputStream会首先读入这个标识头!
Read More
