当我无法访问服务器时,如何从客户端关闭套接字连接?

时间:2013-12-23 09:33:24

标签: java sockets

/*after socket.close(); socket.isConnected() returns "true" why ? */
package example.servertest;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;

public class ClientConn
{
   public void startClient()
   {
      String serverName = "localhost";
      int port = Integer.parseInt("8080");

      Socket client = null ;
      OutputStream outToServer = null ;
      DataOutputStream out = null ;
      try
      {
         System.out.println("Connecting to " + serverName
                             + " on port " + port);
         client = new Socket(serverName,port);
         System.out.println("Just connected to "
                      + client.getRemoteSocketAddress());
         outToServer = client.getOutputStream();
         PrintWriter pw = new PrintWriter(outToServer);
         pw.write("Hello ");
         pw.flush();
         pw.close();

         /*out =  new DataOutputStream(outToServer);
         out.writeUTF("Hello from "
                      + client.getLocalSocketAddress());*/
         /*InputStream inFromServer = client.getInputStream();
         DataInputStream in =
                        new DataInputStream(inFromServer);
         System.out.println("Server says " + in.readUTF());*/

      }catch(IOException e)
      {
         e.printStackTrace();
      }finally{
          try {
              /* out.flush();
              out.close();
              outToServer.flush();
              outToServer.close(); */// closes the socket
              /*client.shutdownInput();
              client.shutdownOutput();*/

              client.close();
   System.out.println("isConnected : "+client.isConnected()+"\nisClosed : "+client.isClosed()+"\nisBound : "+client.isBound());

        } catch (IOException e) {

        }
      }
   }
}

描述: 上面的代码从Apache Server创建一个“套接字连接”然后关闭它。但是从客户端关闭Socket后它返回“socket.isConnected()= true”..我不明白为什么?

2 个答案:

答案 0 :(得分:1)

Socket.isConnected()告诉您是否连接了套接字。你做了,所以它返回true。它没有告诉您有关套接字是端点的连接的状态。只读EOS就可以了。

答案 1 :(得分:0)

您无需担心这一点。链接状态将保持打开一段时间,直到它被处置。请参阅java doc中的Socket.isConnected:

public boolean isConnected()
Returns the connection state of the socket.
Note: Closing a socket doesn't clear its connection state, which means this method will return true for a closed socket (see isClosed()) if it was successfuly connected prior to being closed.