2012-04-08 182 views
0

我在客戶端和服務器之間彈跳對象時遇到了問題。客戶端服務器通信故障

創建一個對象。更新一些字段。發送到服務器。 (這部分作品)

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(); 
.... 

請幫我理解問題

+0

你能展示創建'Socket'的代碼嗎? – 2012-04-08 02:29:21

+0

它就像'Socket sock = new Socket(serverName,SERVER_PORT);' – JAM 2012-04-08 02:30:28

+1

這可能不是問題,但仍然:爲什麼你有'oos.writeObject(thisObject); oos.close();' and 'toServer.println(oos); toServer.flush();'在第一步?你不會只需要第一對線?是否可以'PrintStream.println()'甚至接受一個'ObjectOutputStream'作爲參數,這是否有意義? – 2012-04-08 02:33:25

回答

2

我的猜測是你使用相同的Socket來發送和接收客戶端。當您關閉客戶端上的ObjectOutputStream時,會關閉底層的OutputStream,這會關閉sock。然後,當您嘗試在下面重用它時,它已關閉並引發異常。

取而代之的是,在客戶端代碼中關閉資源之前等待事務完成(順便提一句,這應該在finally塊中完成)。或者,如果等待有問題,請改用新的Socket

+0

好電話保羅。這似乎是我看到的確切問題。 – JAM 2012-04-08 02:47:54

+0

@JAM很高興能幫到你! – 2012-04-08 02:48:28