2017-10-13 201 views
1

這是我第一次socket程序。
我的要求是,android客戶端問一個問題,並通過套接字從ubuntu服務器接收答案。
在我的客戶端,我從套接字創建了BufferedInputStream和BufferedInputStream。BufferedOutputStream.close()會讓BufferedInputStream被關閉嗎?

Socket client = new Socket(); 
InetSocketAddress isa = new InetSocketAddress(my_host, 8888); 
client.connect(isa, 10000); 
inputStream = new BufferedInputStream(client.getInputStream()); 
outputStream = new BufferedOutputStream(client.getOutputStream()); 

我遇到一個奇怪的現象:由於我的客戶通過發送的OutputStream請求並調用其close(),然後調用inputStream.read()會得到java.net.SocketException異常:關閉套接字錯誤。但我的client.isConnected()仍然返回true。

try { 
    outputStream.write("who_are_you".getBytes()); 
    outputStream.flush(); 
    outputStream.close(); // inputStream will be invalid if I call this line. 

    Log.i(TAG, "client: " + client.isConnected()); // client still return true 
    byte[] b = new byte[1024]; 
    String data = ""; 
    int length; 
    // I will receive java.net.SocketException: Socket is closed as I call below code 
    while ((length = inputStream.read(b)) > 0) // If length <= 0, it means exit. 
    { 
    Log.i(TAG, "receive message, length: " + length); 
    data += new String(b, 0, length); 
    Log.i(TAG, "receive message: " + data); 
    } 
} catch (java.io.IOException e) { 
    Log.w(TAG, "socket connection fail"); 
    e.printStackTrace(); 
} 

我知道如果我不調用outputStream.close(),我可以避免這種情況。但我只是很好奇它爲什麼會發生?這是正常結果嗎?

+0

是的,如果你關閉一個流,其他流也將被關閉。和插座。 – greenapps

+0

在finally塊中關閉您的流 – HomeIsWhereThePcIs

+0

您是否檢查過服務器是否意外關閉了連接? – Robert

回答

1

關閉任何套接字輸入流或輸出流將在套接字本身上調用關閉。因此,除非要關閉連接,否則不需要關閉它們。

至於你的支票,請參閱的javadoc上Socket#isConnected()方法(https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#isConnected()

公共布爾isConnected()

返回套接字的連接狀態。

注意:關閉套接字不會清除其連接狀態,這意味着如果在關閉之前它成功連接,則此方法將爲封閉套接字返回true(請參閱isClosed())。