2013-11-23 41 views
-2

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

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继承Thread {

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

可以使用setSoTimeOut(int timeout)功能。看这里Socket如何使用setSoTimeOut函数。

使用指定的超时(以毫秒为单位)启用/禁用SO_TIMEOUT。 如果将此选项设置为非零超时,则与此套接字关联的 InputStream上的read()调用将仅阻塞此 时间量。如果超时到期,将引发一个 java.net.SocketTimeoutException异常,但Socket仍然是 有效。该选项必须在进入阻止 操作之前启用才能生效。超时时间必须> 0。零时间 被解释为无限超时。

+0

感谢您的回复... –

+0

我做到了前面,但是,它连续打印“插座异常”你setSoTimeOut()函数中给 –

+0

什么时候? –

相关问题