我有一個相當複雜的項目,歸結爲一個簡單的客戶端/服務器通過對象流進行通信。奇怪的Java套接字行爲(連接,但不發送)
一切工作完美的連續兩個連接(我連接一次,工作,斷開,然後再次連接,工作,並斷開連接)。客戶連接,完成業務,然後關閉。服務器成功地關閉了對象輸出流和套接字,沒有IO錯誤。
當我第三次嘗試連接時,連接似乎要經過(ServerSocket.accept()方法通過併成功創建ObjectOutputStream)。然而,沒有數據通過。 inputStream.readUnshared()方法只是阻塞。
我採取了以下措施內存:
- 當談到時間來關閉插座,所有正在運行的線程停止,所有的對象都清零了。
- 在每次調用writeUnshared()方法 後,ObjectOutputBuffer將被刷新並重置爲 。
有沒有人遇到類似的問題,或者沒有人有任何建議嗎?恐怕我的項目很大,所以複製代碼是有問題的。
項目歸結爲:
服務器主
ServerSocket serverSocket = new ServerSocket(port);
while (true) {
new WorkThread(serverSocket.accept()).start();
}
工作線程(服務器)
public void run() {
ObjectInputBuffer inputBuffer = new ObjectInputBuffer(new BufferedInputStream(socket.getInputStream()));
while (running) {
try {
Object myObject = inputBuffer.readUnshared();
// do work is not specified in this sample
doWork(myObject);
} catch (IOException e) {
running = false;
}
}
try {
inputBuffer.close();
socket.close();
} catch (Exception e) {
System.out.println("Could not close.");
}
}
CLIENT
public Client() {
Object myObject;
Socket mySocket = new Socket(address, port);
try {
ObjectOutputBuffer output = new ObjectOutputBuffer(new BufferedOutputStream(mySocket.getOutputStream()));
output.reset();
output.flush();
} catch (Exception e) {
System.out.println("Could not get an input.");
mySocket.close();
return;
}
// get object data is not specified in this sample. it simply returns a serializable object
myObject = getObjectData();
while (myObject != null) {
try {
output.writeUnshared(myObject);
output.reset();
output.flush();
} catch (Exception e) {
e.printStackTrace();
break;
} // catch
} // while
try {
output.close();
socket.close();
} catch (Exception e) {
System.out.println("Could not close.");
}
}
謝謝大家誰可能能夠幫助!
你有使用readUnshared與readObject的原因嗎?這看起來對我來說很危險。 – mdma 2010-05-21 21:12:27