簡體   English   中英

Java:嘗試使用objectoutputstream / objectinputstream讀取對象-崩潰

[英]Java: Trying to read object with objectoutputstream/objectinputstream - crashes

在我的服務器類上,我正在通過ObjectOutputStream編寫2D char數組,客戶端使用ObjectInputStream讀取此數組。 之后,我嘗試通過相同的ObjectOutputStream將另一個2D數組發送到相同的ObjectInputStream但是程序崩潰。 我想我的換行符留在ObjectOutputStream但是我不確定如何擺脫它。 我嘗試了inFromServ.read()inFromServ.readLine()inFromServ.flush() 沒有一個可以解決問題= /。 任何幫助,將不勝感激!

客戶代碼:

ObjectInputStream inFromServ = new ObjectInputStream(socket.getInputStream());
printBoard((char[][])inFromServ.readObject()); //Prints the first 2D char array fine

System.out.println(inFromServ.readObject()); //Reads in a string fine
System.out.println(inFromServ.readObject()); //Reads in another string fine

System.out.println("Your shots board:"); //Writes this out fine
printBoard((char[][])inFromServ.readObject()); //Crashes here

服務器代碼:

ObjectInputStream in = new ObjectInputStream(clients[0].getInputStream());
ObjectOutputStream out=new ObjectOutputStream(clients[0].getOutputStream());
char p1brd[][]=new char[10][10];
char p1shots[][]=new char[10][10];

out.writeObject(p1brd); //Writes out the first board fine
out.writeObject("some string"); //Writes this string fine
out.writeObject("some more string"); //Writes this string fine
out.writeObject(p1shots); //Don't even think it gets here... If i put a thread.sleep(10000) before this line it still crashes instantaneously after writing "some more string"

客戶端處於while(true)循環內。 一旦printBoard((char [] [])inFromServ.readObject()); 第二次被調用時,我的try / catch抓住了它,並一遍又一遍地發出catch語句,直到我停止程序為止。

它根本不會“崩潰”,它會引發 異常,並且您的邏輯中存在一個錯誤,即您不會在遇到異常時放棄閱讀。 SocketTimeoutException以外的套接字讀取任何異常都是致命的,唯一正確的響應是關閉套接字。 停止閱讀; 拋棄客戶

下次您報告“崩潰”時,請提供實際的異常和堆棧跟蹤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM