无法断开插座

时间:2013-12-18 15:16:58

标签: java sockets tcpclient

这是我的tcpClient类:

import java.io.*;
import java.net.*;

public class tcpClient
{
private String _ip;
private int _port;
private Socket _clientSocket;

public tcpClient(String IP, int Port)
{
    _ip = IP;
    _port = Port;
}

public boolean createSocket()
{
    boolean retSt = false;

    try
    {
        _clientSocket = new Socket(this._ip, this._port);
        retSt = true;
    }
    catch (UnknownHostException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return retSt;
}

public boolean disposeSocket()
{
    boolean retSt = false;

    try
    {
        _clientSocket.shutdownInput();
        _clientSocket.shutdownOutput();
        _clientSocket.close();

        retSt = true;
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return retSt;
}

public boolean isConnected()
{
    return _clientSocket.isConnected();
}
}

这是我的主要方法:

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;

    public class cos
    {
    public static void main(String[] args)
    {
    tcpClient client = new tcpClient("192.168.10.39", 1234);
    client.createSocket();
    System.out.println(client.isConnected());
    client.disposeSocket();
    System.out.println(client.isConnected());
    client.createSocket();
    System.out.println(client.isConnected());
    client.disposeSocket();
    System.out.println(client.isConnected());
        }
    }

这是我的控制台输出:

true
true
true
true

为什么我无法与服务器断开连接?

1 个答案:

答案 0 :(得分:1)

来自java doc

  

注意:关闭套接字不会清除其连接状态,这意味着   对于已关闭的套接字,此方法将返回true(请参阅isClosed())if   它在被关闭之前已成功连接。