当前位置: 技术问答>java相关
close() 怎么关不掉socket? socket应该怎么关闭?
来源: 互联网 发布时间:2015-05-03
本文导语: 我现在在写一段和c通信的程序其中一段为: private DataInputStream socketReader; private DataOutputStream socketWriter; public void test() { Socket client = null; try { client = new Socket("202.60.1.1",1611); socketReader = new ...
我现在在写一段和c通信的程序其中一段为:
private DataInputStream socketReader;
private DataOutputStream socketWriter;
public void test() {
Socket client = null;
try {
client = new Socket("202.60.1.1",1611);
socketReader = new DataInputStream(new BufferedInputStream(client.getInputStream()));
socketWriter = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
。。。。。。。。。。。。。。
} catch (UnknownHostException e) {
System.out.println("Error setting up socket connection: unknown host"+e);
} catch (IOException e) {
System.out.println("Error setting up socket connection: " + e);
}
finally {
try { socketWriter.close();
socketReader.close();
if (client != null) {
System.out.println("the socketClient is not closed, it will be closed");
client.close();
if (client != null)
System.out.println("the socketclient have wrong");
}
}catch (IOException e){
System.out.println(e);
}
}
为什么不能关闭?因为打印结果为:
the socketClient is not closed, it will be closed
the socketclient have wrong
关闭后client应该为null吧? 我看书中是这么判断的,不知是否有错?
请问怎么关闭?谢谢!
private DataInputStream socketReader;
private DataOutputStream socketWriter;
public void test() {
Socket client = null;
try {
client = new Socket("202.60.1.1",1611);
socketReader = new DataInputStream(new BufferedInputStream(client.getInputStream()));
socketWriter = new DataOutputStream(new BufferedOutputStream(client.getOutputStream()));
。。。。。。。。。。。。。。
} catch (UnknownHostException e) {
System.out.println("Error setting up socket connection: unknown host"+e);
} catch (IOException e) {
System.out.println("Error setting up socket connection: " + e);
}
finally {
try { socketWriter.close();
socketReader.close();
if (client != null) {
System.out.println("the socketClient is not closed, it will be closed");
client.close();
if (client != null)
System.out.println("the socketclient have wrong");
}
}catch (IOException e){
System.out.println(e);
}
}
为什么不能关闭?因为打印结果为:
the socketClient is not closed, it will be closed
the socketclient have wrong
关闭后client应该为null吧? 我看书中是这么判断的,不知是否有错?
请问怎么关闭?谢谢!
|
close只是通知虚拟机断开连接,但在缓冲区中还有数据的情况下,由虚拟机判断这次传输完毕才能断开,你用close()无法控制。
非要强行断开要用
shutdownInput() /shoudownOutput!
不过不常用。
非要强行断开要用
shutdownInput() /shoudownOutput!
不过不常用。
|
client.close()调用过后client就会为null吗?
if (client != null)
System.out.println("the socketclient have wrong");
难道client不为null,就说明它没有close()?
请恕我才疏学浅,呵呵~~
if (client != null)
System.out.println("the socketclient have wrong");
难道client不为null,就说明它没有close()?
请恕我才疏学浅,呵呵~~