2015-06-02 25 views
-1

我现在在Android手机上创建一个简单的TicTacToe游戏。 我使用java服务器来处理多人部分,但是当我将玩家和'新'ObjectInputStream配对时,它会抛出异常。java.io.StreamCorruptedException:无效的流头:74001057

java.io.StreamCorruptedException: invalid stream header: 74001057 

这是我的服务器代码时创建一个新的游戏主题:

public GameThread(Socket Player1, Socket Player2) { 
    this.Player1 = Player1; 
    this.Player2 = Player2; 
    System.out.println("GameThread Started!"); 
    //Exception throw at the codes below 
    new ReceiveMessagesThread(this.Player1, this.Player2).start(); 
    new ReceiveMessagesThread(this.Player2, this.Player1).start(); 
} 

这是我的服务器代码在游戏线程接收消息:

// This is an inner class. 
private class ReceiveMessagesThread extends Thread { 

    private Socket SourceClient, DestinationClient; 

    ReceiveMessagesThread(Socket SourceClient, Socket DestinationClient) { 
    this.SourceClient = SourceClient; 
    this.DestinationClient = DestinationClient; 
    } 

    @Override 
    public void run() { 
    while (true) { 
     try { 
     // Exception throw at the line below 
     ObjectInputStream in = new ObjectInputStream(this.SourceClient.getInputStream()); 

     switch (in.readByte()) { 
      case ServerGlobal.BOARD_STATUS: 
      GameBoard = (char[][]) in.readObject(); 
      SendBoardStatus(this.DestinationClient); 
      break; 
     } 
     } 
     catch (java.io.StreamCorruptedException ex) { 
     ex.printStackTrace(); 
     break; 
     } 
     catch (IOException | ClassNotFoundException ex) { 
     Logger.getLogger(GameThread.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 
    } 
} 
+1

您应该在问题中发布相关代码(即在这种情况下发送和接收消息的代码),而不是链接到整个项目。这会让更多的人了解你的问题,你更有可能得到答案。 –

+0

@KErlandsson编辑。 对不起,因为我虽然使用线程,但问题可能发生在其他地方,我不知道。 所以我张贴在这里~~ –

+0

整个项目你可能想看看例如这样的问题:http://stackoverflow.com/questions/23262160/java-io-streamcorruptedexception-invalid-stream-header-54657374 –

回答

-1

如果输出的通过单独的字符将字符数组分成ObjectOutputStream,那么您应该通过字符读取它,而不是数组。

此外,检查的ObjectOutputStreamObjectInputStream一致的使用。在你的github代码中,你在一些地方使用DataInputStream

还要确保socket.getInputStream()的每个包装new ObjectInputStream()匹配socket.getOutputStream()new ObjectOutputStream()的相应解包。或者更好的做法是,将套接字流仅包装在ObjectInputStreamObjectOutputStream中,而不是每次读取/写入内容。

0

往前走循环的ObjectInputStream的创建。它试图读取由同行的ObjectInputStream放置在那里的流标题,您应该只创建一次。这些流应该在套接字的生命中持续存在,而不是为每次发送或接收重新创建。

相关问题