在我的服务器类上,我正在通过ObjectOutputStream编写2D char数组,客户端使用ObjectInputStream读取此数组。之后,我尝试通过相同的ObjectOutputStream
向相同的ObjectInputStream
发送另一个2D数组,但是程序崩溃了。我想我的换行符留在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
以外的套接字读取任何异常都是致命的,唯一正确的响应是关闭套接字。停止阅读;抛弃客户
下次您报告“崩溃”时,请提供实际的异常和堆栈跟踪。
关于java - Java:尝试使用objectoutputstream/objectinputstream读取对象-崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13697587/