ソケットプログラムは初めてのことです。
私の要件は、アンドロイドクライアントが質問をし、ソケット経由で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());
私は奇妙な行動が発生します。私のクライアントは、出力ストリームで要求を送信し、その近くに()を呼び出すと、その後、
java.net.SocketExceptionがを取得しますinputStream.read()を呼び出し:ソケットはエラーを閉じています。しかし、私の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()を呼び出さないとこれを避けることができます。しかし、私はなぜそれが起こるのか非常に興味がありますか?それは正常な結果ですか?
はい、1つのストリームを閉じると、他のストリームも閉じます。そして、ソケット。 – greenapps
finallyブロックでストリームを閉じる – HomeIsWhereThePcIs
誤って接続を終了した場合、サーバーをチェックしましたか? – Robert