ObjectInputStream导致崩溃

时间:2013-12-02 17:05:17

标签: java objectoutputstream

当我尝试从服务器发送一个对象时,我的计算机似乎崩溃了,第27行尝试接收该对象,我想我得到了一个无效的类型代码:0一次但通常只是崩溃所以我必须重新启动

          new Thread(){
          public void run(){
              boolean sent = false;
              boolean threadStarted = false;
              while(true){
                  if(game.changedTurns){
                     System.out.println(game.changedTurns);
                     if(!sent){
                        try{
                            System.out.println("attempt to send from player");
                            out.writeObject(game.getSquareColors());
                            System.out.println("sent");
                            sent = true;
                            //Thread.sleep(500);
                            sent = false;
                            }
                            catch(Exception ex){
                                System.out.println("player1 " +ex.getMessage());  
                            }
                          }
                      }if(!threadStarted)                       
                          threadStarted = true;
                          new Thread(){
                          public void run(){
                              while(true){
                                  try{
                                      Object ob = in.readObject();  // line 27  

                                      System.out.println("Player received");
                                  }
                                  catch(Exception e){
                                      System.out.println("player2 "+e.getMessage());  
                                  }
                              }
                          }
                      }.start();
                  }
              }
          }.start();
      }

一个对象从另一个客户端发送到服务器,服务器接收并尝试在第16行发送对象:

 class Opponent implements Runnable{    
    ObjectInputStream in2;
    ObjectOutputStream out;
    Opponent(ObjectInputStream in2, ObjectOutputStream out){
        this.in2 = in2;                                                             //from opponent to player
        this.out = out;
    }
    public void run(){                                  
        while(true){
            try{
                System.out.println("from opponent to server waiting");
                Object o2 = in2.readObject();
                if(o2 instanceof Color[]){
                    System.out.println("fee");
                    out.writeObject(o2);                  //line 16
                    out.flush();
                }
            }
            catch(Exception e){
                System.out.println("S2 " +e.getMessage());
            }
        }
    }
}

}

1 个答案:

答案 0 :(得分:1)

对象I / O流在开始传输对象之前相互发送一些标头,因此我的建议是在结束1创建第一个输出流,最后2创建输入流然后在结束1创建输入流并在结束2创建输出流,反之亦然 计算机崩溃似乎很奇怪,这个通常的对象I / O流错过使用