1

在我的服务器类上,我正在通过 ObjectOutputStream 写入一个 2D 字符数组,客户端使用 ObjectInputStream 读取它。之后我尝试通过相同ObjectOutputStream的方式发送另一个二维数组,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 语句,直到我停止程序。

4

1 回答 1

1

它根本不会“崩溃”,它会引发异常并且您的逻辑中有一个错误,当您遇到异常时您不会放弃阅读。任何从套接字读取的异常SocketTimeoutException都是致命的,唯一正确的响应是关闭套接字;停止阅读;并放弃客户。

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

于 2012-12-04T09:07:02.007 回答