新的ObjectInputStream()块

public class SerProg { static ServerSocket ser=null; static Socket cli=null; static ObjectInputStream ins=null; static ObjectOutputStream outs=null; public static void main(String[] args) { try { ser=new ServerSocket(9000,10); cli=ser.accept(); System.out.println("Connected to :"+cli.getInetAddress().getHostAddress()+" At Port :"+cli.getLocalPort()); ins=new ObjectInputStream(cli.getInputStream()); outs=new ObjectOutputStream(cli.getOutputStream()); String str=(String)ins.readObject(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

和客户

 public class SerProg { /** * @param args */ static ServerSocket ser=null; static Socket cli=null; static ObjectInputStream ins=null; static ObjectOutputStream outs=null; public static void main(String[] args) { // TODO Auto-generated method stub try { ser=new ServerSocket(9000,10); cli=ser.accept(); System.out.println("Connected to :"+cli.getInetAddress().getHostAddress()+" At Port :"+cli.getLocalPort()); ins=new ObjectInputStream(cli.getInputStream()); outs=new ObjectOutputStream(cli.getOutputStream()); String str=(String)ins.readObject(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

连接已成功建立,但在服务器代码行中

 ins=new ObjectInputStream(cli.getInputStream()); 

代码停止但不继续,可能是什么问题?

您需要在连接两侧的ObjectInputStream之前创建ObjectOutputStream (!)。 创建ObjectInputStream ,它会尝试从InputStream读取对象流标头。 因此,如果尚未创建另一侧的ObjectOutputStream ,则没有要读取的对象流标头,并且它将无限期地阻塞。

或者用不同的方式:如果双方首先构造ObjectInputStream ,两者都将阻止尝试读取对象流头部,在创建ObjectOutputStream之前不会写入该对象流头部(在行的另一侧); 这将永远不会发生,因为双方都在ObjectInputStream的构造函数中被阻止。

这可以从ObjectInputStream(InputStream in)的Javadoc ObjectInputStream(InputStream in)推断出来:

从流中读取序列化流头并进行validation。 此构造函数将阻塞,直到相应的ObjectOutputStream已写入并刷新标头。

这也在Esmond Pitt的Java基础网络部分3.6.2中描述。