如何在java中关闭客户端套接字?

时间:2013-11-23 08:42:27

标签: java sockets

与客户建立连接后,如果一段时间内未收到数据如何关闭客户端连接?

public class Server_X_Client {
public static void main(String args[]){


Socket s=null;
ServerSocket ss2=null;
System.out.println("Server Listening......");
try{
    ss2 = new ServerSocket(4445); // can also use static final PORT_NUM , when defined
ss2.setSoTimeout(5000);
}
catch(IOException e){
e.printStackTrace();
System.out.println("Server error");

}

while(true){
    try{
        s= ss2.accept();
        System.out.println("connection Established with --> "+s.getRemoteSocketAddress());
        ServerThread st=new ServerThread(s);
        st.start();

    }

catch(Exception e){
    e.printStackTrace();
    System.out.println("Connection Error");

}
}

}

}

类ServerThread扩展了线程{

String line=null;
BufferedReader  is = null;
PrintWriter os=null;
Socket s=null;

public ServerThread(Socket s){
    this.s=s;
}

public void run() {
try{
    is= new BufferedReader(new InputStreamReader(s.getInputStream()));
//
    os=new PrintWriter(s.getOutputStream());

}catch(IOException e){
    System.out.println("IO error in server thread");
}

try {
    line=is.readLine();

    while(line.compareTo("QUIT")!=0){

        os.println(line);
        os.flush();
    System.out.println("Data recieved is : "+ line);

        line=is.readLine();
    }   
} catch (IOException e) {

    line=this.getName(); //reused String line for getting thread name
    System.out.println("IO Error/ Client "+line+" terminated abruptly");
}
catch(NullPointerException e){
    line=this.getName(); //reused String line for getting thread name
    System.out.println("Client "+line+" Closed");
}

finally{    
try{
    System.out.println("Connection Closing..");
    if (is!=null){
        is.close(); 
        System.out.println(" Socket Input Stream Closed");
    }

    if(os!=null){
        os.close();
        System.out.println("Socket Out Closed");
    }
    if (s!=null){
    s.close();
    System.out.println("Socket Closed");
    }

    }
catch(IOException ie){
    System.out.println("Socket Close Error");
}
}//end finally
}
}

1 个答案:

答案 0 :(得分:1)

您可以使用setSoTimeOut(int timeout)功能。请参阅此处Socket如何使用setSoTimeOut功能。

  

使用指定的超时启用/禁用SO_TIMEOUT,以毫秒为单位。   将此选项设置为非零超时,对()调用read()   与此Socket关联的InputStream将仅阻止此操作   多少时间。如果超时到期,a   引发了java.net.SocketTimeoutException,尽管Socket仍然存在   有效。必须在进入阻止之前启用该选项   操作有效。超时必须> 0.超时为零   被解释为无限超时。