我在客戶端和服務器之間彈跳對象時遇到了問題。客戶端服務器通信故障
創建一個對象。更新一些字段。發送到服務器。 (這部分作品)
SomeObject thisObject = new SomeObject();
thisObject.setSomeValue(13); // update object to be sent
PrintStream toServer = new PrintStream(sock.getOutputStream());
ObjectOutputStream oos = new ObjectOutputStream(toServer);
oos.writeObject(thisObject);
oos.close();
toServer.println(oos); // send object to server
toServer.flush();
權在此之後,服務器進一步更新了一些值,並將其設置爲1919年;
ObjectInputStream objFromClient = new ObjectInputStream(new BufferedInputStream(
sock.getInputStream()));
Served thisObject = (Served) objFromClient.readObject();
thisObject.setSomeValue(1919);
服務器然後將對象返回給客戶端
toClient = new PrintStream(sock.getOutputStream());
ObjectOutputStream oos = new ObjectOutputStream(toClient);
oos.writeObject(thisObject);
oos.close();
objFromClient.close();
sock.close();
但在時機成熟時拿起對象返回客戶端上的..程序失敗,並關閉socket例外
ObjectInputStream objFromServer = new ObjectInputStream(
new BufferedInputStream(sock.getInputStream())); //java.net.SocketException: Socket is closed
thisObject = (Served) objFromServer.readObject();
....
請幫我理解問題
你能展示創建'Socket'的代碼嗎? – 2012-04-08 02:29:21
它就像'Socket sock = new Socket(serverName,SERVER_PORT);' – JAM 2012-04-08 02:30:28
這可能不是問題,但仍然:爲什麼你有'oos.writeObject(thisObject); oos.close();' and 'toServer.println(oos); toServer.flush();'在第一步?你不會只需要第一對線?是否可以'PrintStream.println()'甚至接受一個'ObjectOutputStream'作爲參數,這是否有意義? – 2012-04-08 02:33:25