Java close()是否允许关闭BufferedInputStream?
这是我第一次使用socket程序Java close()是否允许关闭BufferedInputStream?,java,android,sockets,Java,Android,Sockets,这是我第一次使用socket程序 我的要求是android客户端提出问题,并通过套接字从ubuntu服务器接收答案 在客户端,我从套接字创建BufferedInputStream和BufferedInputStream Socket client = new Socket(); InetSocketAddress isa = new InetSocketAddress(my_host, 8888); client.connect(isa, 10000); inputStream = new Bu
我的要求是android客户端提出问题,并通过套接字从ubuntu服务器接收答案
在客户端,我从套接字创建BufferedInputStream和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:Socket已关闭错误。但是我的客户机.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();
}
试试看{
write(“你是谁”。getBytes());
outputStream.flush();
outputStream.close();//如果调用此行,则inputStream将无效。
Log.i(标记“client:+client.isConnected());//client仍然返回true
字节[]b=新字节[1024];
字符串数据=”;
整数长度;
//我将收到java.net.SocketException:当我调用下面的代码时,套接字已关闭
while((length=inputStream.read(b))>0)//If length关闭套接字输入流或输出流都将调用套接字本身上的close。因此,除非要关闭连接,否则不需要关闭它们
关于您的检查,请参阅Socket#isConnected()
method()上的javadoc
公共布尔值未连接()
返回套接字的连接状态
注意:关闭套接字不会清除其连接状态,这意味着如果已关闭的套接字在关闭之前已成功连接,则此方法将为已关闭的套接字返回true(请参阅isClosed())
是的,如果您关闭一个流,其他流也将关闭。以及套接字。在最后一个块中关闭您的流如果服务器意外关闭连接,您是否检查了服务器?