這是我第一次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(),我可以避免這種情況。但我只是很好奇它爲什麼會發生?這是正常結果嗎?
是的,如果你關閉一個流,其他流也將被關閉。和插座。 – greenapps
在finally塊中關閉您的流 – HomeIsWhereThePcIs
您是否檢查過服務器是否意外關閉了連接? – Robert