2016-03-15 22 views
0

我正嘗試在兩個應用程序之間實現全雙工TCP連接。無法更正全雙工代碼中的StreamCorruptedException

我的想法的要點是要做到以下幾點:

客戶

socket.connect(ServerAddress,Timeout); 
socketArray.add(socket); 
outputStream = new ObjectOutputStream(socket.getOutputStream()); 
outputStream.writeObject(message); 
outputStream.flush(); 

/** Wait for reply**/ 
inputStream = new ObjectInputStream(socket.getInputStream()); 
message  = (Message)inputStream.readObject(); 

if (message.type == X) { 
    replyToServer(message,socketArray); 
} 

replyToServer(Message,socketArray) { 
    for(Socket socket : socketArray) { 
     outputStream = new ObjectOutputStream(socket.getOutputStream()); // **getting streamCorruptedException** here 
     outputStream.writeObject(message); 
     outputStream.flush(); 

    } 

} 

服務器

在這裏,我聽傳入連接,並依賴於消息類型,我想在更改消息的某些參數後回覆它。

inputStream = new ObjectInputStream(clientSocket.getInputStream()); //notice inputStream and outputStream are created only once here, maybe that is the issue ? 
outputStream = new ObjectOutputStream(clientSocket.getOutputStream()); 
while ((message = (Message)inputStream.readObject()) != null) { 
    if (message.type == Y) { 
    message.type = X ; //notice this is used in Client code 
    outputStream.writeObject(message); 
    outputStream.flush();   
    } else if (message.type == X) { 
    // don't send anything to client, we are done processing this message 
    } 
} 

在谷歌環顧四周後,我得到了一些想法,ObjectInputStream和ObjectOutputStream必須以某種方式同步。但我沒有得到具體的理解。如果有人可以在我的代碼中指出錯誤,這將會有所幫助。

代碼流:

  1. 客戶端將消息發送到與消息Y型服務器,詢問信息。
  2. 服務器看到類型Y,在對象中設置信息,將消息類型更改爲X,並回復客戶端。
  3. 客戶端收到所有其他人的回覆。 注意:有5個應用程序同時運行服務器和客戶端。因此,客戶在繼續之前會等待所有其他人的回覆。

現在客戶端必須將接收到的信息發送給所有5個應用程序,並在replyToServer方法中執行此操作。那裏發生異常。

PS:這是僞代碼,如果需要了解更多詳細信息以瞭解代碼流,請在評論中告訴我。

實際棧跟蹤

err: java.io.StreamCorruptedException 
err: at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1530) 
err:  at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1483) 

.....` 

回答

0
outputStream = new ObjectOutputStream(socket.getOutputStream()); // **getting streamCorruptedException** here 

不可能。當您執行new ObjectInputStream(...)時,您在另一端獲得StreamCorruptedException: invalid type code AC

原因是你已經爲同一個套接字創建了多個ObjectOutputStreams,但是沒有在對等體上創建對應的多個ObjectInputStreams。您應該在套接字的兩端使用相同的對象輸入和輸出流。

while ((message = (Message)inputStream.readObject()) != null) { 

這也是無效的。 ObjectInputStream.readObject()在流結束時不返回空值。任何時候你寫一個null都可以返回null。當拋出EOFException時,循環應該終止。