2012-04-11 22 views
0

我有一個客戶端服務器應用程序,其中我使用java serversocket(服務器端)和套接字(客戶端)與java.nio選擇器工具。我通過ObjectInput/Output Streams使用序列化對象在客戶端和服務器之間交換消息。StreamCorruptedException接收到多個數據包

下面是用於從服務器這是相當標準的當服務器的時間很短的跨度內寫入多個消息和所述客戶端接收它們

enter code here 

var msg:CommunicationMessage = null 
    var buf:ByteBuffer = ByteBuffer.allocate(1024); 
    var numBytesRead:Int = 0 

    try { 
     // Clear the buffer and read bytes from socket 
     buf.clear(); 
     //println("Before Read") 



     numBytesRead = sChannel.read(buf) 


     //println("After Read " + numBytesRead) 


     numBytesRead match { 

      case -1 => 
      println("Something Wrong with the Channel") 

      case 0 => 
      //println("Nothing to read") 

      case _ => 
      //println("Read some bytes") 
      // To read the bytes, flip the buffer 
      buf.flip(); 

      // Read the bytes from the buffer ...; 
      // see Getting Bytes from a ByteBuffer 
      val bis:ByteArrayInputStream = new ByteArrayInputStream (buf.array()); 
      val ois:ObjectInputStream = new ObjectInputStream (bis); 
      msg = ois.readObject().asInstanceOf[CommunicationMessage]; 

      println("\n\n") 
      println("Received Message from Server") 

      msg.msgType match { 

       case CommunicationConstants.COMM_MSG_TYPE_RSP => 
        println("updating server info") 
        updateServerInfo(msg.msgData) 

       case CommunicationConstants.COMM_MSG_TYPE_IND => 
        if (serverAccepted) updateClientUI(msg) 

      } 

     } 

    } catch { 

     case e:StreamCorruptedException => 
     println("Stream Corruption Exception received " + e.getCause()) 

     case e:IOException => 
     // Connection may have been closed 
     println("IO Exception received" + e.getCause()) 
    } 
enter code here 

一切工作除了情況細接收消息的階代碼一起放入緩衝區並導致StreamCorruptedException。據我所知,objectinputstream不能在傳入字節流中的多個序列化對象之間分隔,因此它會拋出這個無效的流錯誤。此外,即使我已經把捕捉它的例外,程序仍然掛起。

這可能是一個解決方案。 ?

1)根據長度字段在消息中創建我自己的分隔符以標識消息邊界。

2)我也讀過某個地方在每次接收後關閉套接字並開始一個新套接字。不知道這將如何幫助。

Plz建議。

在此先感謝

回答

0

您需要發送分組ObjectOutputStream超越了它的內容的長度。然後你知道有多少傳入數據屬於每個流,你可以相應地構建你的ByteArrayInputStream

相關問題