FAQ_04_Socket关闭

最近一直在与socket打交道,所以自认为跟他很熟,但是事实却非如此!

下面代码主要用来关闭已经连接过的socket

/** * 断开已连接服务器 * * */ public void closeSocket(Socket socket) { if(socket != null) { if(socket.isConnected()) { try { socket.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } } }

然后,我在客户端调用该方法来关闭socket,做了如下测试:

//关闭socket closeSocket(socket); //关闭socket后,测试判断socket是否为空 if(socket == null) { System.out.println("socket is null!"); } else { System.out.println("socket is not null!"); } //关闭socket后,测试判断socket是否已经关闭 if(socket.isClosed()) { System.out.println("socket is closed!"); } else { System.out.println("socket is not null!"); } 

我原以为关闭socket之后,socket对象就为null,看看打印结果吧?!

socket is not null! socket is closed! 

ok,socket不为null只是closed!


你可能感兴趣的:(FAQ_04_Socket关闭)