有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在java中关闭客户端socket?

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

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) 个答案

  1. # 1 楼答案

    可以使用setSoTimeOut(int timeout)函数。请参见此处Socket如何使用setSoTimeOut函数

    Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.