Java:尝试使用objectoutputstream / objectinputstream读取对象 - 崩溃

时间:2012-12-04 06:54:16

标签: java objectoutputstream objectinputstream

在我的服务器类上,我通过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"

客户端在一段时间(真实)循环中。一旦printBoard((char [] [])inFromServ.readObject());第二次调用我的try / catch获取它并一遍又一遍地喷出catch语句,直到我停止程序。

1 个答案:

答案 0 :(得分:1)

它根本没有'崩溃',它抛出 异常,你的逻辑中有一个错误,你不会放弃阅读有一个例外。从SocketTimeoutException以外的套接字读取任何异常都是致命的,唯一正确的响应是关闭套接字;停止阅读;并放弃了客户。

下次报告'崩溃'时,请提供实际的异常和堆栈跟踪。